A
A
Alexey R2014-04-02 23:56:14
Java
Alexey R, 2014-04-02 23:56:14

How in Java (Android) to change the color of Layout several times when clicking on one button?

Good evening everyone. I just recently started learning Java. That is, I learn a programming language and try to apply everything at once in practice directly on my examples. Naturally, I encounter many problems, but gradually I solve them, of course, not without help. Including the "residents" of this site.
And now again I want to ask you to help me and explain the code example, and perhaps offer my own version.
My task is the following. There is one RelativeLayout and Button as well as a variable int n = 0. I need to make it so that when the button is pressed, the color of the Layout changes. If there were several buttons, then I would not have any difficulties, but I don’t understand the implementation mechanism with one button. To be honest, I decompiled a similar application for educational purposes, and I can’t make out some points that I don’t understand. Pleases only one thing, the train of thought was correct.
Now the OnClickListener handler for the code is Activity, then I give an example of clicking on the button

@Override
  public void onClick(View v) {
    switch (this.n) {
    case 0:
      rltLayout.setBackgroundColor(Color.GREEN);
      this.n = 1;
      return;
    case 1:
      rltLayout.setBackgroundColor(Color.RED);
      this.n = 2;
      return;

    default:
      break;
    }
  }

Too much this for me, I can't figure out how this code works. I don’t understand the line switch (this.n) I would understand if it were switch (v.getID()) but we have nothing to look for by ID. And I don't understand this.n = 1;
return;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2014-04-03
@SashaSkot

In the field of the object this.n writes some state (0 or 1). When the button is pressed, the current value is checked and the background color of the layout changes depending on it. Further, probably, following the logic, other values ​​are written to the same variable and return interrupts the execution of the switch.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question