Domanda

I want my ImageButton image to be changed after some time after last click.

ImageButton b = ...
b.setOnClickListener(new OnClickListener() {

  @Override
  public void onClick(View v) {
    b.removeCallbacks(null);
    b.postDelayed(new Runnable() {
      @Override
      public void run() {
        b.setImageResource(android.R.drawable.ic_delete);
      }
    }, 1500);
  }
});

This code doesn't work. Line removing callbacks returns true, but doesn't remove any callbacks. If I'm clicking button again and again it will change image after 1,5s after first click.

È stato utile?

Soluzione

Try this one?

 public void onClick(View v) {
    b.removeCallbacks(clickRunnable);
    b.postDelayed(clickRunnable, 1500);
  }


  Runnable clickRunnable = new Runnable() {
      @Override
      public void run() {
        b.setImageResource(android.R.drawable.ic_delete);
      }
    };

Altri suggerimenti

To make it clearer:

define handler and runnable as private fields. That will make them reusable on all button clicks

private Handler mHandler = new Handler();
private Runnable mClickRunnable = new Runnable() {
      @Override
      public void run() {
        mInmageView.setImageResource(android.R.drawable.ic_delete);
      }
    };

in onClick()

mHandler.removeCallbacks(mClickRunnable);
mHandler.postDelayed(mClickRunnable, 1500);

First line removes previous callbacks(we don't need them anymore)

Second line begins new callback

The removeCallbacks method removes(cancels the execution of) a previously posted runnable. You have to put the same (Runnable) object as an argument of removeCallbacks if you wish to stop its execution:

_myRunnable = new Runnable() {...};
...
b.removeCallbacks(_myRunnable);
b.postDelayed(myRunnable, 1500);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top