How to setContentView in a fragment?

前端 未结 5 1797
说谎
说谎 2020-11-29 05:53

Now I\'ve got this fragment which i want to use setContentView with but so far i cant find how. You can see my case in the code below, im not trying to inflate a layout, im

相关标签:
5条回答
  • 2020-11-29 06:17

    Return the view instance you want to use:

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            return inflater.inflate(R.layout.ads_tab, container, false);
        }
    
    0 讨论(0)
  • 2020-11-29 06:22

    You dont call setContentView in fragments, in fact you need to return a View from onCreateView.

    Try replacing:

    setContentView(new SampleView(this));
    

    With this:

    return new SampleView(this);
    
    0 讨论(0)
  • 2020-11-29 06:24

    Also it's not safe to call getActivity() from onCreateView(). Make sure you call it in or after onActivityCreated(), as at this point your Fragment is fully associated with the Activity. Check Fragment's lifecycle.

    Fragments

    0 讨论(0)
  • 2020-11-29 06:27

    In activities we need to set the view using setContentView(R.layout.main)

    Where as in fragments we need to override onCreateView() to set the desired view.

    0 讨论(0)
  • 2020-11-29 06:36

    As explained already, you need to return the view in case of fragments. But still if you want to use it just like setContentView(), you can do so in following way.

    1.Put this code snippet wherever you had to put setContentView()

    View v = inflater.inflate(R.layout.activity_home, container, false);
    

    2.Now if you want to access something from xml file, you can do so by using

    chart = v.findViewById(R.id.chart);
    

    3. And in the end of OnCreateView() you will have to put

    return v;
    

    Full example :

      public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
    
    
        View v = inflater.inflate(R.layout.activity_home, container, false);
    
        chart = v.findViewById(R.id.chart);
    
        return v;
       }
    
    0 讨论(0)
提交回复
热议问题