Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use onClickListener method of Button on a ListView

I have a custom ListView which contains a Button. The function of this button is Delete button. Whenever user click to this button, the current Row will be deleted.

  • How can I do it?
  • How can I set onClickListener for this button?
  • How can I catch the row Id which this button is on?

Thanks in advance.

like image 903
detno29 Avatar asked Jul 21 '12 10:07

detno29


3 Answers

In your Custom Adapater class's getView()

buttonDelete.setOnClickListener(new OnClickListener()
{
  @Override
  public void onClick(View v)
   {
     //  Use position parameter of your getView() in this method it will current position of Clicked row button
    // code for current Row deleted...              
   }
});
like image 105
user370305 Avatar answered Nov 15 '22 04:11

user370305


First, that will be very easy for you to handle the click on this item. You just have to add a listener with: myButton.setOnClickListener(mBuyButtonClickListener). This action is usually done on the getView(...) implementation of your ListView.

Your listener can know what is the item position of the button by using myListView.getPositionForView(myButton). Look at this sample of the listener :

private OnClickListener mBuyButtonClickListener = new OnClickListener() {
    @Override
    public void onClick(View v) {
        final int position = getListView().getPositionForView(v);
        if (position != ListView.INVALID_POSITION) {
            //DO THE STUFF YOU WANT TO DO WITH THE position
        }
    }
};

When this is done, you should have problems to handle the click on the item itself and some other touch event propagation.

So, you should read this article that fully describes the use of multiple touchable areas inside a ListView. It will be very helpful.

like image 41
eyal-lezmy Avatar answered Nov 15 '22 03:11

eyal-lezmy


Use this inside the getView method of your adapter class.

holder.button.setOnClickListener(new OnClickListener()
{
  @Override
  public void onClick(View v)
   {

   }
});
like image 39
Manikandan Avatar answered Nov 15 '22 03:11

Manikandan