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 SingleFragmentActivity.java 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.app.Fragment;


import android.app.FragmentManager;
import android.os.Bundle;

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

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment);

FragmentManager manager = getFragmentManager();
Fragment fragment = manager.findFragmentById(R.id.fragmentContainer);

if (fragment == null) {
fragment = createFragment();
manager.beginTransaction()
.add(R.id.fragmentContainer, fragment)
.commit();
}
}
}

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.

Reference

And the example in the link

@Override
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);
    scroller.addView(text);
    text.setText(Shakespeare.DIALOGUE[getShownIndex()]);
    return scroller;
}

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