Tuesday 5 April 2011

Android ListView Example

This is another tutorial on android application development. It's about ListView where you have several options or list of options for the users to view or select.

We'll show you how:-
1. to create the ListView
2. to add items into the ListView
3. to pop up the item chosen by the user

Step 1
Go to res/layout and open up the main.xml file. Add the following code:-

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

Step 2
Go to src folder and open up your .java file. Add the following code:-

import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;


public class activityTestListView extends Activity 
{
    private ListView lv1;
    private String lv_arr[]={"Option 1","Option 2","Option 3"};
         
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
   {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        lv1=(ListView)findViewById(R.id.ListView01);
        lv1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , lv_arr));
        lv1.setTextFilterEnabled(true);
        

        //this line is what will happen when user click on the item
        lv1.setOnItemClickListener(new OnItemClickListener()
         {
        @Override
         public void onItemClick(AdapterView<?> a, View v, int position, long id)
            {
            AlertDialog.Builder adb=new AlertDialog.Builder(activityListView.this);
            adb.setTitle("LVSelectedItemExample");
            adb.setMessage("Selected Item is = "+lv1.getItemAtPosition(position));
            adb.setPositiveButton("Ok", null);
            adb.show();
            }
         });

    }
}

Note:-
~ replace "Option 1", "Option 2" and "Option 3" with your own preference

Run the project and click on any item from the listing.

Roger,
mytikus

No comments: