How to setContentView in a fragment?

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


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);

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);
    }

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;
   }