Skip to main content

Simple ListView Adapter and list item select

When you are using a listview in your applications many a times you will write your own adapter to display item. But if your list is very simple showing a list of strings, you can use inbuilt adapters like ArrayAdapter, SimpleCursorAdapter etc.

ArrayAdapter

Let us look at an example

 <?xml version="1.0" encoding="utf-8"?>  
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
     android:orientation="vertical"   
     android:layout_width="fill_parent"  
     android:layout_height="fill_parent" >  
      <ListView   
          android:layout_height="wrap_content"   
          android:id="@+id/listView1"   
          android:layout_width="match_parent"  
          android:layout_margin="20dp">  
     </ListView>  
 </LinearLayout>  


And add these lines to the onCreate method of the activity.

     super.onCreate(savedInstanceState);  
     setContentView(R.layout.main);  
     String []s = new String[] {"Lorem","Ipsum","dolor","sit","amet"};  
     ListView lv = (ListView)findViewById(R.id.listView1);  
     lv.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,s));  

                 
So constructor of ArrayAdapter just needs the array to be displayed in the list, the context i.e. activity and the textview resource id.  Now our listview looks like this


If you want to change the appearance of your list, you can define your own list view as shown. Add another xml file with just a textview . Do not use any layout.

Let your tv.xml in layout folder look like this.

 <TextView xmlns:android="http://schemas.android.com/apk/res/android"  
    android:text="TextView" 
    android:id="@+id/textView1"  
    android:background="#0489B1"  
    android:textColor="#000000"  
    android:layout_width="fill_parent"  
    android:layout_height="wrap_content"    
    android:layout_margin="20dp"  
    android:padding="5dp"></TextView>  

Now use this as layout in arrayadpter

 lv.setAdapter(new ArrayAdapter<String>(this, R.layout.tv,s));





Next step will be write a listener to the list. You should attach an OnItemClickListener to this listview.

  lv.setOnItemClickListener(new OnItemClickListener() {  
   @Override  
   public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,  
    long arg3) {  
    ListView lv = (ListView) arg0;  
    TextView tv = (TextView) lv.getChildAt(arg2);  
    String s = tv.getText().toString();  
    Toast.makeText(SamplesActivity.this, "Clicked item is"+s, Toast.LENGTH_LONG).show();    
   } });  

Instead of Toasting, you can perform any required processing. 

What if you want to use the list for selecting one of the items? Again the simplest way to use this is to use android.R.layout.simple_list_item_single_choice

       lv.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_single_choice,s));
        lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);   
Now our list lets us select exactly one item


How do you find out which item is selected from the listview? 
Let us use a button, on click of which we will display the selected item of the list.

Modified main.xml is

 <?xml version="1.0" encoding="utf-8"?>  
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  android:background="#0489B1"   
 android:layout_width="fill_parent"  
  android:layout_height="fill_parent"   
 android:orientation="vertical">  
  <ListView  
  android:layout_height="wrap_content"  
  android:id="@+id/listView1"  
  android:layout_width="match_parent"   
 android:divider="#00ffffff"  
  android:dividerHeight="10dp"   
 android:layout_margin="20dp">  
 </ListView>  
  <Button android:text="OK"   
 android:id="@+id/button1"  
  android:layout_width="wrap_content"   
  android:layout_height="wrap_content"   
  android:layout_gravity="center_horizontal">  
 </Button>  
  </LinearLayout>  


Let us add the button and onclicklistener to it.

     btn =(Button) findViewById(R.id.button1);  
     btn.setOnClickListener(new OnClickListener() {   
            @Override  
            public void onClick(View v) {  
                 int p = lv.getCheckedItemPosition(); 
                 if(p!=ListView.INVALID_POSITION) {
                    String s = ((TextView) lv.getChildAt(p)).getText().toString();
                    Toast.makeText(MainActivity.this, "Selected item is " + s, Toast.LENGTH_LONG).show();
                }else{
                    Toast.makeText(MainActivity.this, "Nothing Selected..", Toast.LENGTH_LONG).show();
                }   
           }  
     });  

      

 

Listview with multiple selection


Finally let us see how to select multiple elements from the list. 

First of all, change the list mode multiple select


lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
 


We should also modify our adapter as

 lv.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice, s));
     

Then we should use lv.setCheckedItemPositions() which returns a sparse boolean array. The array elements are true if that item is selected



 btn.setOnClickListener(new OnClickListener() {    
   @Override  
   public void onClick(View v) {  
        SparseBooleanArray sp = lv.getCheckedItemPositions();  
        StringBuffer str = new StringBuffer();  
        for(int i=0;i<sp.size();i++){  
               if(sp.valueAt(i)==true){  
                     String s = ((TextView) lv.getChildAt(i)).getText().toString();  
                     str = str.append(" "+s);  
               }  
        }    
        Toast.makeText(SamplesActivity.this, "Selected items are "+str.toString(), Toast.LENGTH_LONG).show();    
   }  
  });  

 
And, our multi select list is ready!


Comments

  1. Very nice tutorial. Thanks for this. It saved my day... Thanks a ton...

    ReplyDelete
  2. Very good one, still:) One issue: in case of one item selection list view, if someone will click on OK button, but does not select anything, the exception will raise.

    ReplyDelete
    Replies
    1. Thank you Jacek for pointing out that error. getCheckedItemPosition returns INVALID_POSITION if nothing is selected. I have made that correction now.

      Delete
    2. Great. There is one more issue. If the number of items on the ListView is longer than one page the OK button will not be visible (or reachable).

      Delete

Post a Comment

Popular posts from this blog

Drawables in Android - Layer drawable

Let us see how to use layer drawable. You can have two or more bitmaps on different layers to create such a drawable

Using xml:

You should use layer-list in your xml file to create layerdrawable. Here is layer.xml
<?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <item> <bitmap android:src="@drawable/whiteicon" android:gravity="top|left"/> </item> <item> <bitmap android:src="@drawable/blueicon" android:gravity="top|left"/> </item> <item> <bitmap android:src="@drawable/redicon" android:gravity="top|left"/> </item> </layer-list>
We are using three different bitmaps whiteicon.png, redicon.png and blueicon.png which are present in /res/drawable/mdpi folder. All these are of different sizes and aligned to top left. This drawab…

DatePickers in Android

DatePicker is a view which lets the user select a date showing a calendar or 3 spinners for dd, mm and yy.

Let us see how to use this.
Easy Method: To use a DatePicker you can use DatePickerDialog. This can be created and shown programmatically too.

publicvoidonCreate(Bundle b){/*********/ Button btn =(Button)findViewById(R.id.btn); btn.setOnClickListener(new View.OnClickListener(){@OverridepublicvoidonClick(View v){ showPickerDialog();}});}privatevoidshowPickerDialog(){ DatePickerDialog dtPickerDlg =new DatePickerDialog(this,this, 2017,10,20); dtPickerDialog.show();}

In our xml file, let us have a button and in the onclick listener of the button, let us display the date picker dialog - we call showPickerDialog.

In showPickerDialog,  we are using a random date to initialize.

The first  parameter is the context. Second parameter is the class which implements the interface OnDateSetListener. Next three parameters are year, month (Jan is 0) and …