user1275838
user1275838

Reputation: 3

Android:Disable Button in listview

I added a button in a listview item, and after the button is clicked, I want the button is disabled. I used the below setOnClickListener for my button in the custom adapter, but the problem is when i clicked on a button, the button of another list item will also be disabled. For example, when I clicked the button of item 1, the button of item 1 then is disabled, but the item 4's button will also be disabled at the same time although i didn't click on it. And also, when I scroll up and down, all item's button just enable and disable randomly. Anyone know why is this happening?

   holder.viewBtn.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        holder.viewBtn.setEnabled(false);
                        showInfo();                 
                    }           });

Upvotes: 0

Views: 3334

Answers (2)

Shubhayu
Shubhayu

Reputation: 13552

I was so frustrated when I first faced this problem!

The problem here is that the listview just doesn't remember the state of the button. Dunno if it is a bug but anyways I needed a way out and this is what I did.

I believe you are using a custom adapter with a viewholder. Means you are on the right path. You need to keep an array of booleans whose size is equal to the number of items in your list. in your btnClick() set the state of the item in the array.

Now everytime you scroll, or do soemthing that makes the list redraw, getView() is called. Put a check in your getView() for the items state and enable/disable it. One more thing, Make sure you implement both if{} and else{} for the check.

if(checked){
    holder.viewBtn.setEnabled(false);
}else{
    holder.viewBtn.setEnabled(true);
}

if you don't do this you'll see weird behaviours. One more thing if you are using the

if(convertview == null){
    //create the holder
}else{
   convertview = getTag();
}

method, make sure you populate the state after the above step.

I have not seen your implementation but I had to pop up a button in the item and then delete the item from the list using it. So I had to take extra care for maintaining the state.

So be careful about the states once the underlying data has changed.

Sorry about the long post but the problem is such :(

I found a link that has the solution in a basic format

Upvotes: 2

P Varga
P Varga

Reputation: 20229

This is happening because ListView reuses Views in an erroneous manner. Either implement your own ListAdapter without View reuse or file a bug report with Google

Upvotes: 1

Related Questions