Can't add HeaderView to ListFragment

Here is the code where I add the list to my fragmet list:

public void onAttach(Activity activity) { super.onAttach(activity); System.err.println("Fragment Attach"); String[] MyList = {"Item 1","Item 2","Item 3","Item 4","Item 5"}; System.err.println("File Row ID" + Integer.toString(R.layout.file_row)); ArrayAdapter<String> aa = new ArrayAdapter<String>(getActivity(), R.layout.file_row, MyList); //Trying to add a Header View. TextView tv = (TextView) activity.findViewById(R.layout.file_row); tv.setText(R.string.FileBrowserHeader); this.getListView().addHeaderView(tv); //Setting the adapter setListAdapter(aa); } 

However, the string this.getListView (). addHeaderView (tv); gives me an error

06-11 15: 24: 46.110: ERROR / AndroidRuntime (8532): Called: java.lang.IllegalStateException: Content view not created yet

And the program will fail.

Can someone tell me what I am doing wrong?

+4
source share
1 answer

The problem is that you add the title too quickly. The error is caused by the fact that you are trying to find not yet created views.

Life cycle for a fragment (source: http://developer.android.com/reference/android/app/Fragment.html )

  • onAttach (Activity), called as soon as the fragment is associated with its activity.
  • onCreate (Bundle) called to initially create the fragment.
  • onCreateView (LayoutInflater, ViewGroup, Bundle) creates and returns the view hierarchy associated with the fragment.
  • onActivityCreated (Bundle) tells the fragment that its activity has completed its own Activity.onCreate.
  • onStart () makes the fragment visible to the user (depending on its triggering activity).
  • onResume () forces the fragment to interact with the user (based on its active activity, which resumes).

As you can see, you are trying to use views in onAttach, but views do not exist until onCreateView! Try moving your code to onActivityCreate, what happened after all existing views

+9
source

All Articles