Ethan Allen
Ethan Allen

Reputation: 14835

How do I populate a ListFragment in Android?

I have seen all kinds of tutorials about how to turn an Activity into a ListActivity to populate a ListView, but nothing for ListFragments. I have two tabs with a Fragment under each. Here is what my fragment currently looks like.... can someone give me some idea on how I can do this?

public class MainFragment extends ListFragment {    

String[] items = { "12 Monkeys", "(500) Days of Summer", "Chariots of Fire" };

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){      
        return inflater.inflate(R.layout.fragment_main, container, false);
 }
}

and here is the XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

</LinearLayout>

I'm trying to get items to show in the ListView.

Upvotes: 1

Views: 1741

Answers (1)

LuxuryMode
LuxuryMode

Reputation: 33741

You don't need to inflate a view containing a listview inside of your ListFragment. Simply create an adapter, give it some data and in onCreate() of your fragment call setListAdapter(). Then somewhere else (presumably in your Activity) you can then add this fragment with a fragmentmanager.

Upvotes: 3

Related Questions