how to set setContentView in fragment

前端 未结 4 462
慢半拍i
慢半拍i 2021-01-27 05:37

I am trying to call a library in a fragment but dont know how to set it in a fragment I have done it in the main activity but I am getting an error in setting the setContentVie

4条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-27 05:57

    On a fragment you don't call setContentView explicitly, you return the view after inflating it, as you are. So instead of calling setContentView consider adding the view aboutPage to rootView or one of its children views.

    For example, say your layout R.layout.fragment_navigation contains a LinearLayout (or any other ViewGroup for that matter) with an ID of content. You would do this, before your return statement:

    LinearLayout content = (LinearLayout) rootView.findViewById(R.id.content);
    content.addView(aboutPage); //<-- Instead of setContentView(aboutPage)
    

    You'll have to adjust this to your layout, I don't know what's inside it.

    Full example

    fragment.xml

    
    
    
    

    CustomFragment.java

    public class FragmentExample extends Fragment {
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
    
            ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.fragment, container, false);
            Element versionElement = new Element();
            versionElement.setTitle("Version 6.2");
    
            Element adsElement = new Element();
            adsElement.setTitle("Advertise with us");
    
            View aboutPage = new AboutPage(getActivity())
                    .isRTL(false)
                    .addItem(versionElement)
                    .addItem(adsElement)
                    .addGroup("Connect with us")
                    .addEmail("elmehdi.sakout@gmail.com")
                    .addFacebook("the.medy")
                    .addTwitter("medyo80")
                    .addYoutube("UCdPQtdWIsg7_pi4mrRu46vA")
                    .addPlayStore("com.ideashower.readitlater.pro")
                    .addInstagram("medyo80")
                    .addGitHub("medyo")
                    .create();
    
            viewGroup.addView(aboutPage);
            return viewGroup;
        }
    }
    

提交回复
热议问题