How to setContentView in a fragment?

前端 未结 5 1811
说谎
说谎 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: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;
       }
    

提交回复
热议问题