A
A
Alexey R2014-03-27 17:25:17
Android
Alexey R, 2014-03-27 17:25:17

How to implement multiple actions with one button?

Good day to all. My question is - is it possible to set several actions on one button?
That is, for example, you press once - the color of the application changes to red, the second time - to green, etc. I understand that this will be the switch method, but I have only one button, what should I sort through there, I don’t understand? How to do it? Write please...

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vladimir Yakushev, 2014-03-27
@VYakushev

@AlexRudkowskij suggested a working solution in principle, but not very beautiful in terms of OOP and design patterns. I dare to suggest another option. For each color, we implement several fields that implement View.OnClickListener. At the same time, in the handler of each, we first change the color of the button to the desired one, and then prescribes the buttons for the next listener class. Well, when the Activity starts, we assign one of the listeners.

redButtonListener = new View.OnClickListener() {
  @Override           
  public void onClick(View v) {
    myButton.setBackgroud(R.drawable.green);
    myButton.setOnClickListener(greenButtonListener);
    // выполняем дополнительные действия
  }
}

greenButtonListener = new View.OnClickListener() {
  @Override           
  public void onClick(View v) {
    myButton.setBackgroud(R.drawable.red);
    myButton.setOnClickListener(redButtonListener);
    // выполняем дополнительные действия
  }
}

Thus we achieve:
1. Clarity in the code. No need to keep in mind which index should be responsible for which color. The code is self-documented.
2. Easy to edit when adding new colors.
3. Each click handler in a separate place, not in if or swith noodles

A
Alexey Rudkovsky, 2014-03-27
@AlexRudkowskij

You misunderstand your task :(

A
Alexey Rudkovsky, 2014-03-27
@AlexRudkowskij

In general, here's how to do it:
1) Make an event for the button. Make an array of colors.
2) When you click on the button, set the first color. Add one to the variable (this variable is the color index from the array)
And so on... When you click on the button, set the color (colors[i]), and add one (i++).
More or less like this :-)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question