Pages

Tuesday, 12 August 2014

Creating Simple List View



List View is a view group that displays a list of scrollable items. This list items are automatically inserted to the list using an  Adopter that pulls content from a source such as an array or database query and converts each item result into a view that's placed into the list.


Simple Program show the ListView Layout

Step 1: Create a new Project
              File->New->Android Application Project.

Step 2: In Package Explorer Right Click on res/layout folder under your project
              Go to New->Android XML file->listview.xml (you can use any
                  name you wish).

Step 3: Open the newly created xml file(listview.xml) and write the below
              code to define the listview in xml.


listview.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>


 Step 4: To set this new xml view as the intial view of your app.
            Go to MainActivity.java you will see setContentView(R.layout.activity_main) inside onCreate(). Change R.layout.activity_main to R.layout.listview.


MainActivity.java


package com.example.hello_world;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends Activity {

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

        ListView lv = (ListView) findViewById(R.id.listView1);

        String[] values = new String[] { "Android List View",
                "Adapter implementation", "Simple List View In Android",
                "Create List View Android", "Android Example",
                "List View Source Code", "List View Array Adapter",
                "Android Example List View" };

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

        lv.setAdapter(adapter);
    }
}




No comments:

Post a Comment