将片段添加到特定视图实例

时间:2015-01-22 17:57:07

标签: android view append fragment childviews

给定一个View实例,如:

View view = layoutInflater.inflate(R.layout.my_fragment, null);

是否可以在此实例中添加片段?类似的东西:

MyFragment fragment = new MyFragment();
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.add(view, R.id.myLinearLayout, fragment);
fragmentTransaction.commit();

注意FragmentTransaction.add调用。我想将我的片段添加到视图实例中,就在我的R.layout.my_fragment中存在的R.id.myLinearLayout中,并附加到特定的视图实例。

我希望它足够清楚。

1 个答案:

答案 0 :(得分:1)

怎么样:

View view = layoutInflater.inflate(R.layout.my_fragment, null);
view.post(new Runnable {
    public void run() {
        MyFragment fragment = new MyFragment();
        FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
        fragmentTransaction.add(R.id.myLinearLayout, fragment);
        fragmentTransaction.commit();
    }
});

因此,一旦将视图添加到布局中,Runnable就会运行。