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

Copy to clipboard

In my upcoming app, I have codes which I display. These are some times lengthy, and I want the app to be able to copy this to clipboard. Once it is in clipboard, users can paste it anywhere. So how do you copy some text from your app to clipboard. You need to use clipboard manager. Clipboard Manager This class sets and gets data for the clipboard using Clipdata objects.  You can get the object of this class using system service.  - using statement context.getSystemService(Context.CLIPBOARD_SERVICE) Example I have a dummy project with a button, onclick of which copies content to clipboard. Here is my activity file package com . hegdeapps . testapp ; import android.content.ClipData ; import android.content.ClipboardManager ; import android.support.v7.app.AppCompatActivity ; import android.os.Bundle ; import android.view.View ; import android.widget.Button ; import android.widget.TextView ; public class MainActivity extends AppCompa

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