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