0

I wonder what is the best way to use one button to support multiple function.

Let's say I have application to play music. There is one "play/pause" button. Should I:

1) Use one button and override its onClickListener to perform different actions (play or pause music)

2) Use one button and one onClickListener where i check what is current state and perform action depending on this state

3) Use two buttons with one onClickListeners for every button and show/hide buttons having only one button visible

4) Something else ?

Is there any pattern or maybe it depends on the situation?

Allan Pereira
  • 2,572
  • 4
  • 21
  • 28
user3921796
  • 117
  • 3
  • 13

4 Answers4

1

Android already has ToggleButton, which automatically tracks a 'checked' state. If you want more than 2 states, then you should probably consider a more appropriate UI element like a Spinner.

IvoDankolov
  • 495
  • 3
  • 13
0

I would use a single button and it's overridden OnClickListener. From there use a switch or if clause to decide the functionality it serves.

0

I think your second way is the best way. Minimal code redundancy and a state machine. It's the cleanest way.

In Android you can also use the third way. Click on the Button, make it invisible, do something and make the other Button visible. Both Buttons have their own onClickListener. It's not complicated but also not really pretty.

Ben
  • 696
  • 9
  • 19
0

in your xml:

<Button
android:tag="Play"
../>

in your activity:

button.setOnClickListener(new OnClickListener() {
   public void onClick(View v) {
     if(((String)v.getTag()).equals("Play")){
        v.setTag("Pause");
         //DO YOUR WORK

     }else{
        v.setTag("Play");
       //DO YOUR WORK
     }       
     }  
});
ugur
  • 3,604
  • 3
  • 26
  • 57
  • It doesn't look like good solution to depends on string as current state. Isn't better to use some variable to store current state? – user3921796 May 04 '16 at 14:33
  • Of course you can. getTag() returns an object what you defined with the setTag(Object tag). Same way also you can consider using setText, getText methods. So this way you can handle button text to inform the user current state of the button. – ugur May 04 '16 at 16:12