Search code examples
androidlistviewandroid-studioadapterbaseadapter

ImageView Button Toggle inside listview


I have a List view of ringtones with a play image view in each row for each ringtone.

This is the view of it.

Like this

Now obviously when a user clicks on a play button it should switch to pause button.

Now I have a problem :

I click on a play button and it will turn into pause button, but in the meantime when I click on a play button from another row it takes two clicks until the second one turns into the pause button.

This is my code :

Adapter

    Product product = (Product) mDataItems.get(position);
    holder.playPause=(ImageView)v.findViewById(R.id.playPause); 
    holder.playPause.setImageResource(product.getPlayPauseId());
    holder.playPause.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
              if (callback != null) {
                  callback.playPauseOnClick(position);
              }      
        }
    });

Activity

    @Override
public void playPauseOnClick(int position) {
    final Product product = productList.get(position);
                if (paused) {
                    product.setPlayPauseId(R.drawable.ic_pause);
                paused=false;
                }else {
                    product.setPlayPauseId(R.drawable.ic_play);
                 paused = true;
                }
                adapter.notifyDataSetChanged();     
    };

I am already guessing the problem is in my condition

if(paused){
  }

I would be grateful if you can offer me a better logic


Solution

  • you are using one pause field for all the rows so the first tap changes its status to true the second tap on the other row changes it to false and the sets the drawable

     product.setPlayPauseId(R.drawable.ic_pause)
    

    on the first row and the third tap works correctly.

    you can define pause field for every product and inside if clause check the products pause filed

    if(product.pause){
        ...
        product.paused = false;
    }else{
        product.paused = true;
    }