以下是我将列表添加到列表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);
}
但是行.getListView()。addHeaderView(tv);给我错误
06-11 15:24:46.110:ERROR / AndroidRuntime(8532):引起:java.lang.IllegalStateException:尚未创建内容视图
程序崩溃了。
谁能告诉我我做错了什么?
答案 0 :(得分:9)
问题是您要过早添加标题视图。 您尝试查找尚未创建的视图时会导致该错误。
片段的生命周期是(来源:http://developer.android.com/reference/android/app/Fragment.html)
正如您所看到的,您正在尝试在onAttach中使用视图,但在onCreateView之前视图不存在!尝试将代码移动到onActivityCreate,这是在视图全部存在之后发生的