How to hide a View programmatically?

前端 未结 3 1367
野趣味
野趣味 2020-11-27 12:11

In my application, I have 2 LinearLayout\'s right above each other. Via a menu option, I want to be able to make the bottom one disappear, and have the top one

相关标签:
3条回答
  • 2020-11-27 12:51

    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
    }
    
    0 讨论(0)
  • 2020-11-27 12:56

    Try this:

    linearLayout.setVisibility(View.GONE);
    
    0 讨论(0)
  • 2020-11-27 13:14

    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.

    0 讨论(0)
提交回复
热议问题