Home > Enterprise >  Change visibility of one button by clicking another button
Change visibility of one button by clicking another button

Time:12-02

I am trying to change visibility of two buttons when pressing one of them.

So say I have an "on" and an "off" button. When I press the on button, I want the on button to hide itself and the off button to show, and vice versa.

How could one do this?

CodePudding user response:

See this example in Kotlin, adapt it for your own needs:

    val onButton = Button(this)
    val offButton = Button(this)
    onButton.setOnClickListener {
        onButton.visibility = INVISIBLE
        offButton.visibility = VISIBLE
    }
    offButton.setOnClickListener {
        onButton.visibility = VISIBLE
        offButton.visibility = INVISIBLE
    }

Or in Java:

    Button onButton = (Button) findViewById(R.id.onButton);
    Button offButton = (Button) findViewById(R.id.offButton);

    onButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            onButton.visibility = INVISIBLE;
            offButton.visibility = VISIBLE;
        }
    });

    offButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            onButton.visibility = VISIBLE;
            offButton.visibility = INVISIBLE;
        }
    });

CodePudding user response:

Basically, you have to inform on to point.

  1. How can I handle the visibility ?
  2. How can I listen to a click event ?

How can I handle the visibility ?

You can handle the visibility of a view by using the enter image description here

  • Related