Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cant add a HeaderView to a ListFragment

Tags:

android

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

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 line this.getListView().addHeaderView(tv); gives me the error

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

And the program crashes.

Can anyone tell me what am I doing wrong?

like image 805
aarelovich Avatar asked Jan 20 '23 12:01

aarelovich


1 Answers

The problem is that you are adding the header view too soon. The error is being caused by you trying to find views that haven't been created yet.

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

  1. onAttach(Activity) called once the fragment is associated with its activity.
  2. onCreate(Bundle) called to do initial creation of the fragment.
  3. onCreateView(LayoutInflater, ViewGroup, Bundle) creates and returns the view hierarchy associated with the fragment.
  4. onActivityCreated(Bundle) tells the fragment that its activity has completed its own Activity.onCreate.
  5. onStart() makes the fragment visible to the user (based on its containing activity being started).
  6. onResume() makes the fragment interacting with the user (based on its containing activity being resumed).

As you can see, you are trying to use views in onAttach, but the views don't exist until onCreateView! Try moving your code to onActivityCreate, which has happened after the views all exist

like image 76
Christopher Souvey Avatar answered Jan 31 '23 04:01

Christopher Souvey