java - onclicklistener timeout?

By : James
Source: Stackoverflow.com
Question!

I have a button which moves and changes the imagebutton immediately on every press, and on every 5th press activates a command. Now I'm trying to get it to timeout if 5 seconds elapses and then have the button disappear. I have been trying with the Handler example (Timeout detection for eventlisteners in Android) but can't figure out exactly where to put the code to get it to work?

public void addListenerOnButton() {
 imageButton = (ImageButton) findViewById(R.id.imageButton1);
 imageButton.setOnClickListener(new OnClickListener() {
    int i=0;
    @Override
    public void onClick(View arg0) {
        i+=1;
        //Move position
        Random r = new Random();
        int buttonHeight;
        int buttonWidth;
        int xPos = r.nextInt(480);
        int yPos = r.nextInt(800);
        imageButton.setX(xPos);
        imageButton.setY(yPos);

        //Change image
        int[] imageIds = {
                R.drawable.pic1,
                R.drawable.pic2,
                R.drawable.pic3,
                R.drawable.pic4,
                R.drawable.pic5,
                R.drawable.pic6,
                R.drawable.pic7,
                R.drawable.pic8,
                R.drawable.pic9,
                R.drawable.pic10

        };
        int randomImageId = imageIds[r.nextInt(imageIds.length)];
        imageButton.setImageResource(randomImageId);
        if(i==5){
            Toast offMsg = Toast.makeText(getBaseContext(),
                    "This is the fifth button press", Toast.LENGTH_SHORT);
            offMsg.show();
            int i=0;
        }
    }
});
}
By : James


Answers

You can do Something like this.

final Button button = findViewById(R.id.button);

final Runnable runnable = new Runnable() {
  @Override public void run() {
    // Replace with your logic.
    button.setOnClickListener(null);
  }
};

button.setOnClickListener(new View.OnClickListener() {
  @Override public void onClick(final View view) {
    //Removing 5 Seconds timer which will remove click listener.
    view.removeCallbacks(runnable);
  }
});

//Removed Click Listener after 5 Seconds.
button.postDelayed(runnable, 5000);

Create a Runnable and add your logic in run method. Whenever you want to start timer use postDelayed(Runnable runnable, long delay) function start timer. And, To remove time just call removeCallbacks(Runnable runnable) and pass the same runnable. this will remove timer.



This video can help you solving your question :)
By: admin