StillLearningToCode StillLearningToCode - 5 months ago 22
Java Question

setContentView(int) not working

i am trying to work through a tutorial and have run across a bit of a snag. the tutorial
implements a class SingleFragmentActivity to host a fragment (with the xml file to go along with it.

My issue is in this class, there is a call to setContentView(int) that is throwing an error, its says it cannot find the method. Isn't setContentView(int) part of the Fragment Class?


import android.os.Bundle;

public abstract class SingleFragmentActivity extends Fragment {
protected abstract Fragment createFragment();

public void onCreate(Bundle savedInstanceState) {

FragmentManager manager = getFragmentManager();
Fragment fragment = manager.findFragmentById(;

if (fragment == null) {
fragment = createFragment();
.add(, fragment)

Answer Source

.app.Fragment has its view initialized in onCreateView. Basically you need to use inflater to inflate your view and return it as root view in onCreateView.


And the example in the link

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    if (container == null) {
        // We have different layouts, and in one of them this
        // fragment's containing frame doesn't exist.  The fragment
        // may still be created from its saved state, but there is
        // no reason to try to create its view hierarchy because it
        // won't be displayed.  Note this is not needed -- we could
        // just run the code below, where we would create and return
        // the view hierarchy; it would just never be used.
        return null;

    ScrollView scroller = new ScrollView(getActivity());
    TextView text = new TextView(getActivity());
    int padding = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
            4, getActivity().getResources().getDisplayMetrics());
    text.setPadding(padding, padding, padding, padding);
    return scroller;

Besides, if you want to use setContentView, use FragmentActivity in the support library.