2

imagine an Android app that has 3 TextViews in a linear layout, one sequentially below the other, then 2 buttons. 1 button needs to hide the second text view, and the second button needs to make it visible again.

The only requirement is that when the second text view goes away, it should not occupy any space, meaning that third text view should occupy its space while it is gone.

I tried this with the INVISIBLE and VISIBLE settings, however, a blank placeholder remains in the place of the second text view.

I tried with GONE, which eliminated the blank space, however I could not make the second text view appear again.

Do you know a way to achieve this?

Example:

////////////////////////////
initial state:
textview1
textview2
textview3
button1
button2

--> user pushes button1

new state:
textview1
textview3
button1
button2

--> user pushes button2

new state: initial state
////////////////////////////

Thanks

user1060551
  • 421
  • 2
  • 11
  • 20

2 Answers2

25

Two ways:

XML

in your XML file. If you want to have initial visibility

android:visibility="gone" <-- hides

or

android:visibility="visible" <-- makes it visible

Java

in java file. For when you need to change it programmatically

textView.setVisibility(View.GONE);//makes it disappear

or

textView.setVisibility(View.VISIBLE);//makes it visible again

Different visibilities:

  • Visible

Says itself: Sets the view to be visible

  • Invisible

Hides the view, but it still occupies space.

  • Gone

Hides the view, and makes it occupy no space.

Zoe
  • 27,060
  • 21
  • 118
  • 148
1

In Kotlin, you can set like this

textView.visibility = if(visible) View.VISIBLE else View.GONE

or you can add the extension on View

fun View.setVisible(visible: Boolean) {
    visibility = if (visible) {
        View.VISIBLE
    } else {
        View.GONE
    }
}

the use it like this

textView,setVisible(true)
Keshav
  • 2,965
  • 3
  • 25
  • 30