Dom.F
Dom.F

Reputation: 17

How do I switch between two views being visible?

I am making an application that helps score a table tennis game. I am at the final stages but I am having trouble with switching the server around every two points. I have given it a lot of thought but I can only get it to switch once. I know it is probably an easy solution but it's just not coming to me.

Here's how I am switching it once. I am using a count each time the button is pressed and when it reaches a number divisible by 2 it switches to the right.. However, using this logic is making it difficult to switch back! Thanks in advance.

    public void serveSwitch() {
    TextView leftServe = findViewById(R.id.leftServe);
    TextView rightServe = findViewById(R.id.rightServe);
    serverCount++;
    if (server.serve=="left") {
        if (serverCount % 2 == 0) {
            rightServe.setVisibility(View.VISIBLE);
            leftServe.setVisibility(View.GONE);
        }

    }

Upvotes: 1

Views: 169

Answers (1)

Zain
Zain

Reputation: 40908

The part I'm struggling with is the logic on how to switch visibility every two points

If I get your point right, you want to toggle the visibility from off to on every two points and vice versa

You can do something like:

...
if (server.serve=="left") {
    if (serverCount % 2 == 0) {

        switch (rightServe.getVisibility()) {
            case View.GONE:
                rightServe.setVisibility(View.VISIBLE);
                break;

            case View.VISIBLE:
                rightServe.setVisibility(View.GONE);
                break;
        }

        switch (leftServe.getVisibility()) {
            case View.GONE:
                leftServe.setVisibility(View.VISIBLE);
                break;

            case View.VISIBLE:
                leftServe.setVisibility(View.GONE);
                break;
        }

    }

}

Note: I left the equality as-is as you say there is no problem with it. but in general you should use .equals() when it comes to compare strings in java.

Upvotes: 3

Related Questions