Sekhar Bhetalam
Sekhar Bhetalam

Reputation: 4545

How to display multiple ListViews in one activity

In my application I need to display multiple (three) listviews at a time sections wise. What is a best way to implement this?

Upvotes: -1

Views: 1348

Answers (2)

Adam
Adam

Reputation: 2570

If you create the ListView's in an XML file, you can just specify the ID attribute like so: android:id="@+id/listView1, providing a different ID for each ListView. In your Java code, you will want to extend Activity and create three ListView objects and point them towards the IDs in your XML file.

Once you have a handle on the ListView's, you want to create a data source and ArrayAdapter<String> for each ListView. I prefer to use ArrayList<String> over the convential String[] simple because, to me, they are easier to use. A working Java sample below would work for a single ListView. Duplicate the variables and objects twice more with differing names for the two other ListViews.

public class MainListActivityExample extends Activity {

    ListView listView1;
    ArrayList<String> lvContents1 = new ArrayList<String>;
    ArrayAdapter<String> lvAdapter1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Tell the method which layout file to look at
        setContentView(R.layout.listViewExample_activity);

        // Point the ListView object to the XML item
        listView1 = (ListView) findViewById(R.id.listView1);

        // Create the Adapter with the contents of the ArrayList<String>
        lvAdapter1 = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, lvContents1);

        // Attach the Adapter to the ListView
        listView1.setAdapter(lvAdapter1);

        // Add a couple of items to the contents
        lvContents1.add("Foo");
        lvContents1.add("Bar");

        // Tell the adapter that the contents have changed
        lvAdapter1.notifyDataSetChanged();
}

In order to add the other two ListViews, create two more ListView objects, two more ArrayList<String> objects, and two more ArrayAdapter<String> objects, each with corresponding names so you know which belongs to which. You can then follow the exact same steps to initialize them.

Upvotes: 0

Deses
Deses

Reputation: 1080

Maybe you want to look into fragments.

http://developer.android.com/guide/components/fragments.html

Upvotes: -2

Related Questions