Fajar Khan Fajar Khan - 2 months ago 5
Android Question

Multiple OnClickListner for a button

I am trying to make a countdown app. i have button it start countdown when it pressed also the countdown text will appear on the same button too. so when user press again i want pause the countdown and hide text on button and if user press button again the countdown will start and text will show again.

So the question is how can i do multiple OnClick event for one button?
i tried the below code but only one

onClick
is working and if i press again it never go on second
onClick
.

play=(Button)findViewById(R.id.play);

play.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

//something
}
});

play.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

//something
}
});


Any help would be appreciated! Thanks!

Answer

Listeners are overwritten. So just use two different ones, and set them according to the state.

public void onCreate( ... ){
    Button mButton = ...
    mButton.setOnClickListener( startListener );

}

View.OnClickListener startListener = new View.OnClickListener() {

    public void onClick( View v ){
       // start countdown
       // show text

       mButton.setOnClickListener( stopListener );
    }
}

View.OnClickListener stopListener = new View.OnClickListener() {

    public void onClick( View v ){
       // stop countdown
       // hide text

       mButton.setOnClickListener( startListener );
    }
}

Or you can use only one listener and change the behaviour depending on a variable

public void onCreate( ... ){
    Button mButton = ...
    mButton.setOnClickListener( listener );

}

View.OnClickListener listener = new View.OnClickListener() {

    public void onClick( View v ){

        if ( isRunning ){ 
           // start countdown
           // show text
        } else { 
           // stop countdown
           // hide text
        }
    }
}
Comments