Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android : How to set onClick event for Button in List item of ListView

I want to add onClick event for buttons used in item of Listview. How can I give onClick event for buttons in List Item.

like image 650
Sagar Dhomane Avatar asked Sep 26 '12 06:09

Sagar Dhomane


4 Answers

In Adapter Class

public View getView(final int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = getLayoutInflater();
    View row = inflater.inflate(R.layout.vehicals_details_row, parent, false);
    Button deleteImageView = (Button) row.findViewById(R.id.DeleteImageView);
    deleteImageView.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            //...
        }
    });
}

But you can get an issue - listView row not clickable. Solution:

  • make ListView focusable android:focusable="true"
  • Button not focusable android:focusable="false"
like image 80
mukesh Avatar answered Nov 07 '22 16:11

mukesh


You can set the onClick event in your custom adapter's getView method..
check the link http://androidforbeginners.blogspot.it/2010/03/clicking-buttons-in-listview-row.html

like image 28
Nermeen Avatar answered Nov 07 '22 15:11

Nermeen


Try This,

public View getView(final int position, View convertView,ViewGroup parent) 
{
   if(convertView == null)
   {
        LayoutInflater inflater = getLayoutInflater();
        convertView  = (LinearLayout)inflater.inflate(R.layout.YOUR_LAYOUT, null);
   }

   Button Button1= (Button)  convertView  .findViewById(R.id.BUTTON1_ID);

   Button1.setOnClickListener(new OnClickListener() 
   { 
       @Override
       public void onClick(View v) 
       {
           // Your code that you want to execute on this button click
       }

   });


   return convertView ;
}

It may help you....

like image 13
Hemant Avatar answered Nov 07 '22 16:11

Hemant


In your custom adapter inside getView method :

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // Do things Here 
    }
});
like image 4
magirtopcu Avatar answered Nov 07 '22 17:11

magirtopcu