Tuesday, April 10, 2012

Multiple onclick events in a list view

Let's say that you have an Android adapter with a few buttons on it and you want the onclick to handle different tasks. How do you handle clicks within the row? Simple. In the xml definition for that adapter row view, assign an onclick. Take a look at the imageview below.
android:onClick="statusGroupClickHandler"
Clicks are handled by statusGroupClick Handler. Code for this gets added to your listactivity in a statusGroupClickHandler().
 <?xml version="1.0" encoding="utf-8"?>  
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   android:layout_width="fill_parent"  
   android:layout_height="75dp"  
   android:orientation="horizontal"  
   android:background="@drawable/gridpaper_row">  
   <ImageView  
     android:id="@+id/liImage"  
     android:tag="togglebutton"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:layout_marginRight="5dp"  
     android:layout_gravity="center_vertical"  
     android:onClick="statusGroupClickHandler"  
     android:src="@drawable/checkmarkuncheckedimage58x54" />  
   <TextView  
     android:id="@+id/liName"  
     style="@style/MediumBlackBoldText"  
     android:layout_width="fill_parent"  
     android:layout_height="wrap_content"  
     android:layout_weight=".5"  
     android:layout_gravity="center_vertical"  
     android:gravity="left|center_vertical" />  
 </LinearLayout>  
 public void statusGroupClickHandler(View v)   
   {  
           Guide item = (Guide) v.getTag();  
           Log.d(TAG, "Item Clicked: " + item.toString());  
 }