Java – Multiple clicks of the same button

Multiple clicks of the same button… here is a solution to the problem.

Multiple clicks of the same button

The idea is that the button can do one thing on the first click and another on the second click.

button_food   = (Button) findViewById(R.id.foodicon_layout);
button_travel = (Button) findViewById(R.id.travelicon_layout);
button_fuel   = (Button) findViewById(R.id.fuelicon_layout);
button_fetch  = (Button) findViewById(R.id.fetchicon_layout);

button_travel.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {

 Perform action on click
        button_food.setVisibility(View.GONE);
        button_fuel.setVisibility(View.GONE);
        button_fetch.setVisibility(View.GONE);
    }
});

In the given example, when the button_travel is clicked, the other buttons will not be visible. When I click the same button again, I want the other buttons to be visible again.

Solution

You can set the visibility of a button by getting its current visibility and toggling it.

button_food   = (Button) findViewById(R.id.foodicon_layout);
button_travel = (Button) findViewById(R.id.travelicon_layout);
button_fuel   = (Button) findViewById(R.id.fuelicon_layout);
button_fetch  = (Button) findViewById(R.id.fetchicon_layout);

button_travel.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {

int visibility = button_food.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE;

 Perform action on click
        button_food.setVisibility(visibility);
        button_fuel.setVisibility(visibility);
        button_fetch.setVisibility(visibility);
    }
});

Writing this way is just a simple if statement

int visibility;
if(button_food.getVisibility() == View.VISIBLE){
     visibility = View.GONE;
} else {
     visibility = View.VISIBLE;
}

Related Problems and Solutions