Capturing Click on a custom listview in Android

Arun picture Arun · Feb 21, 2011 · Viewed 7.3k times · Source

I used a custom XML file created bind my db cursor in a ListActivity. Each item in the XML file has 2 buttons. I want to capture the click event of the button and the position in the list.

This is my XML file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView android:id="@+id/smListName" android:paddingTop="2dip" android:paddingBottom="3dip" android:layout_width="wrap_content"
        android:layout_height="fill_parent" android:textSize="22dip" />
    <Button android:id="@+id/smListCompleted" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_gravity="right" android:textStyle="bold" android:textColor="#0000ff"  />
    <Button android:id="@+id/smListNotCompleted" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_gravity="right" android:textColor="#ff0000" 
        android:textStyle="bold" />
</LinearLayout>

And this is how I'm binding

db = openOrCreateDatabase("ITC", MODE_PRIVATE, null);
Cursor outlets = db.rawQuery("Select s.salesmanid as _id, s.name ...", null);
this.setListAdapter(new SimpleCursorAdapter(this, R.layout.salesmanlist, outlets, new String[] { "name", "complete", "incomplete" }, new int[] {
R.id.smListName, R.id.smListCompleted, R.id.smListNotCompleted }));
db.close();

I'm not using a custom adapter. Now I want to capture the click of smListNotCompleted and smListCompleted along with the row position.

Thanks

Answer

Reno picture Reno · Feb 21, 2011

You will have to use a new adapter. Try to understand the concept behind this before implementing this :

class YourNewAdapter extends SimpleCursorAdapter
{

 public View getView(int position, View convertView, ViewGroup parent)
 {

        View v = convertView;
        LayoutInflater vi = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = vi.inflate(id, null);

         btn = (Button)v.findViewById(R.id.yourbutton);  
         btn.setOnClickListener(YourActivity.this);
         btn.setId(position);

         btn.setText("sometext");

         v.setLongClickable(true);

          }
            return v;
     }
 }

and in your activity

public void onClick(View v)
{
        if(v.getId() == R.id.yourbutton id)
        {
               // do what you want you can also put this on click listener in the getview fn 
        }
    }