添加具有0 containerViewId的片段 [英] Add fragment with 0 containerViewId

查看:60
本文介绍了添加具有0 containerViewId的片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我调用 FragmentTransaction add(片段片段,字符串标签)时,android在哪里添加片段?

我已经编写了这段代码,但是看不到片段的布局.它显示一个空白屏幕.

  @Override受保护的void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);片段片段= new TestFragment();FragmentTransaction ft = getFragmentManager().beginTransaction();ft.add(fragment,"test");ft.commit();}//onCreate公共类TestFragment扩展Fragment {@Nullable@Override公共视图onCreateView(LayoutInflater充气器,ViewGroup容器,捆绑的saveInstanceState){return inflater.inflate(R.layout.frag_layout,container,false);}}//TestFragment 

解决方案

您需要指定布局资源 ID ,因此, FragmentTransaction 可以将您的片段添加到该资源中(容器).

当您调用 FragmentTransaction.add(Fragment,Tag)时,您实际上在调用 FragmentTransaction.add(0,Fragment,Tag),但请注意,"0"不是有效的资源ID.因此,实际上您的片段是在没有任何视图的情况下创建的.

可能会有不带视图的片段,因此该方法实际上用于刚刚创建的片段类型,以进行一些处理,但与布局没有交互作用

Where does android add fragment when I call FragmentTransaction add (Fragment fragment, String tag)

I have written this code, but I can't see fragment's layout. It displays an empty screen.

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Fragment fragment = new TestFragment();
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.add(fragment, "test");
        ft.commit();
    } // onCreate

 public class TestFragment extends Fragment {

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

解决方案

You need to specify layout resource ID so, the FragmentTransaction can add your fragment to that resource (container).

When you call FragmentTransaction.add(Fragment, Tag) you actually calling FragmentTransaction.add(0,Fragment,Tag) and keep in mind "0" is not a valid resource ID. So actually your fragment is created without any view.

It is possible to have fragments without the view so this method actually is used for those types of fragments which just created to do some processing but have no interactions with layouts

这篇关于添加具有0 containerViewId的片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆