Search code examples
androidandroid-layoutkotlintextview

How do I display only textviews that have values?


If I have 10 textviews, how do I efficiently display those that have values and hide those that don't have values without checking if they have values then set the visibility to VISIBLE for each textview. Is there an efficient way of doing this?

Textviews are within a LinearLayout


Solution

  • You will have a place in the code where this check happens anyway.

    If you want a way to remove the boilerplate which this check generates I can suggest using kotlin extension function like this:

    fun TextView.setTextOrGone(text: String?) {
        this.visibility = if (text.isNullOrBlank()) View.GONE else View.VISIBLE
        this.text = text
    }
    
    

    And then set text like this:

    textView.setTextOrGone(value)