Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide a View programmatically?

Tags:

java

android

People also ask

How do you hide a view?

Step 1: Tap on three-dots icon available in the top right side of your post. Step 2: Tap Hide like counts or Hide like and view counts to turn this setting on. Step 3: Tap Unhide Like Counts or Unhide like and view counts to turn this setting off.

How do you hide a view in Java?

Use with setVisibility(int) and android:visibility . This view is invisible, and it doesn't take any space for layout purposes. Use with setVisibility(int) and android:visibility .

How do I set Visibility gone in Kotlin?

Android developers have added an extension androidx. core. view. ViewKt#isVisible to toggle visibility between View.


You can call view.setVisibility(View.GONE) if you want to remove it from the layout.

Or view.setVisibility(View.INVISIBLE) if you just want to hide it.

From Android Docs:

INVISIBLE

This view is invisible, but it still takes up space for layout purposes. Use with setVisibility(int) and android:visibility.

GONE

This view is invisible, and it doesn't take any space for layout purposes. Use with setVisibility(int) and android:visibility.


Try this:

linearLayout.setVisibility(View.GONE);

Kotlin Solution

view.isVisible = true
view.isInvisible = true
view.isGone = true

// For these to work, you need to use androidx and import:
import androidx.core.view.isVisible // or isInvisible/isGone

Kotlin Extension Solution

If you'd like them to be more consistent length, work for nullable views, and lower the chance of writing the wrong boolean, try using these custom extensions:

// Example
view.hide()

fun View?.show() {
    if (this == null) return
    if (!isVisible) isVisible = true
}

fun View?.hide() {
    if (this == null) return
    if (!isInvisible) isInvisible = true
}

fun View?.gone() {
    if (this == null) return
    if (!isGone) isGone = true
}

To make conditional visibility simple, also add these:

fun View?.show(visible: Boolean) {
    if (visible) show() else gone()
}

fun View?.hide(hide: Boolean) {
    if (hide) hide() else show()
}

fun View?.gone(gone: Boolean = true) {
    if (gone) gone() else show()
}