Android UI

Create Simple Listview In Android

Here i explain to you how to create a simple listview which uses built-in Arrayadapter.

1. Add listview container to layout
2. Create an listview adapter with items
3. Set adapter to listview
4. Catch click event
5. Build & Run

Add listview container to layout

add_listview

listview_xml_file

Create an listview adapter

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ListView listView = (ListView) findViewById(R.id.listView);

        // Create Items
        String[] values = new String[] { "Item No 1",
                "Item No 2",
                "Item No 3",
                "Item No 4",
                "Item No 5" };

        //Add items to adapter

        ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
                android.R.layout.simple_list_item_1, android.R.id.text1, values);

Set adapter to listview

 // Set adapter to ListView
 listView.setAdapter(adapter);

Catch click event

 listView.setOnItemClickListener((parent, view, position, id) -> {
     String itemValue = (String) listView.getItemAtPosition(position);
     Toast.makeText(getApplicationContext(), itemValue, Toast.LENGTH_LONG).show();  // Display
     });

All together

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;


public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ListView listView = (ListView) findViewById(R.id.listView);

        // Create Items
        String[] values = new String[] { "Item No 1",
                "Item No 2",
                "Item No 3",
                "Item No 4",
                "Item No 5" };

        //Add items to adapter

        ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
                android.R.layout.simple_list_item_1, android.R.id.text1, values);

        // Set adapter to ListView
        listView.setAdapter(adapter);

       

        listView.setOnItemClickListener((parent, view, position, id) -> {
            String itemValue = (String) listView.getItemAtPosition(position);
            Toast.makeText(getApplicationContext(), itemValue, Toast.LENGTH_LONG).show();  // Display

        });
    }
}

Build & Run

Capture11

About author

Rojer is a programmer by profession, but he likes to research new things and is also interested in writing. Devdeeds is his blog, where he writes all the blog posts related to technology, gadgets, mobile apps, games, and related content.

Leave a Reply

Your email address will not be published. Required fields are marked *