【问题标题】:Android: Fragments: setContentView alternativeAndroid:片段:setContentView 替代
【发布时间】:2011-08-04 08:50:50
【问题描述】:

我正在尝试使用fragments 重写现有项目以将我的应用程序移植到平板电脑上。

我正在用fragments 替换活动。

问题是我不知道setContentView方法等价于什么?除了重写onCreateView,还有什么方法可以创建Fragment's 视图?

【问题讨论】:

    标签: android android-fragments


    【解决方案1】:

    onCreateView() 方法中,您可以返回片段的视图,如下所示:

    @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
    { 
      return inflater.inflate(R.layout.ads_tab, container, false); 
    }
    

    【讨论】:

    • 应该注意这是:@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.ads_tab, container, false); }
    【解决方案2】:

    我不确定你为什么不能使用onCreateView。但这是你可以做的。

    创建LinearLayout对象,保存为mRooLayout成员字段并从onCreateView返回。以下是如何实现setContentView

    void setFragmentContentView(View view)
    {
        LinearLayout.LayoutParams layoutParams = 
                new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, 
                                              ViewGroup.LayoutParams.FILL_PARENT);
        mRootLayout.removeAllViews();
        mRootLayout.addView(view, layoutParams);
    }
    

    【讨论】:

    • 我的问题是我异步加载视图。因此,当操作系统实际视图尚未准备好调用 onCreateView 时。我会试试你的代码,谢谢
    • 你的意思是我可以随时调用onCreateView?或者我应该调用什么来让我的片段重新创建它的视图?
    • 不,您不能致电onCreateView。好吧,您可以,但这不会产生任何影响,并且很可能会弄乱您的片段中的所有内容(如果您在此函数中保存对视图的引用)。此函数只能由操作系统调用。
    • 是的,我明白了。我的意思是我应该调用什么来让操作系统调用该方法?
    • 你什么也做不了。它的生命周期回调。只需重新组织您处理视图的方式。你可以以我的回答为出发点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-10
    • 1970-01-01
    • 2013-01-31
    相关资源
    最近更新 更多