我试图在我的片段中放入一个简单的列表视图。我按原样运行时收到错误。我不希望它与我现有的代码一起工作,但我不知道从哪里开始。任何帮助将不胜感激!
我的代码:
public class Tab1Fragment extends ListFragment {
ListView listView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
LinearLayout theLayout = (LinearLayout) inflater.inflate(R.layout.tab1, container, false);
listView = (ListView)theLayout.findViewById(R.id.ListView01);
return theLayout;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Use an existing ListAdapter that will map an array
// of strings to TextViews
setListAdapter(new ArrayAdapter<String>(getActivity().getApplicationContext(),
android.R.layout.simple_list_item_1, mStrings));
getListView().setTextFilterEnabled(true);
}
private String[] mStrings = {
"Action", "Adventure", "Animation", "Children", "Comedy", "Documentary", "Drama",
"Foreign", "History", "Independent", "Romance", "Sci-Fi", "Television", "Thriller"
};
}
我的运行时错误:
07-19 11:42:45.214: E/AndroidRuntime(19873): FATAL EXCEPTION: main
07-19 11:42:45.214: E/AndroidRuntime(19873): java.lang.RuntimeException: Unable to start activity ComponentInfo{package/package.TabActionBarActivity}: java.lang.IllegalStateException: Content view not yet created
07-19 11:42:45.214: E/AndroidRuntime(19873): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
07-19 11:42:45.214: E/AndroidRuntime(19873): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
07-19 11:42:45.214: E/AndroidRuntime(19873): at android.app.ActivityThread.access$600(ActivityThread.java:123)
07-19 11:42:45.214: E/AndroidRuntime(19873): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
答案 0 :(得分:7)
您应尝试在setListAdapter()
方法中调用onActivityCreated()
。这是因为片段的onCreate()
方法尚未完全创建活动,因为每个片段的生命周期略有不同。
以下是一个类似的问题:Android Fragment onCreateView vs. onActivityCreated
答案 1 :(得分:5)
片段中的一些问题: