繁体   English   中英

如何在Android的片段中放入列表视图?

[英]How to put a listview inside of a fragment in android?

我试图在片段中放入一个简单的listview。 按原样运行时出现错误。 我没想到它可以与当前的代码一起使用,但是我不确定从这里开始。 任何帮助将不胜感激!

我的代码:

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)

您应该尝试在onActivityCreated()方法中调用setListAdapter() 这是因为Activity尚未完全由Fragment的onCreate()方法创建,因为每个生命周期都略有不同。

这是一个类似的问题: Android片段onCreateView与onActivityCreated

您的片段中有几个问题:

  1. 如果您使用的是ListFragment,则在XML布局中,必须具有ID为“ android.R.id.list”的ListView。
  2. 在onViewCreated()而不是onCreate()中调用setListAdapter()方法。 这是因为在onCreateView()之前先调用onCreate()。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM