简体   繁体   中英

How to put a listview inside of a fragment in android?

I'm trying to put a simple listview inside my fragment. I'm getting an error when I run it as is. I wasn't expecting it to work with the current code I have, but I'm not sure where to go from here. Any help would be greatly appreciated!

My code:

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"
    };

}

my runtime error:

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)

You should try calling setListAdapter() in the onActivityCreated() method. This is because the Activity hasn't been completely created by the onCreate() method of a Fragment since the lifecycles of each are slightly different.

Here is a similar question: Android Fragment onCreateView vs. onActivityCreated

A couple of problems in your fragment:

  1. If you are using ListFragment, then in your XML layout, you must have a ListView that has id of 'android.R.id.list'.
  2. Call your setListAdapter() method in onViewCreated() instead of onCreate(). This is because onCreate() is called first before onCreateView().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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