Search code examples
androidxmlkotlintextview

How to keep the Character Count Text View Blank when an Edit text is empty in Android Studio


So I already figured out how to have the word count show during the user typing inside the EditText, but Now I want the character count to be blank when there is no characters in the text field.

Here's a pick of what I am talking about.

enter image description here

And here's the code that is connecting the word count to the Edit Text

itemView.date_time_add.addTextChangedListener(object: TextWatcher{
                override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, end: Int) {
                    itemView.cCount1.text = ""
                }

                override fun onTextChanged(s: CharSequence?, start: Int, count: Int, end: Int) {
                    if (s.isNullOrEmpty()){
                        itemView.cCount1.text = ""
                    }
                }

                override fun afterTextChanged(s: Editable?) {
                    if (s != null) {
                        itemView.cCount1.text = "${225 - s.length} Characters Remaining"
                    }
                }

            } )

Any ideas is welcomed, thank you.


Solution

  • To hide or show the View you can use .visibility property. To show you can use View.VISIBLE, and to hide View.GONE or View.INVISIBLE

    override fun onTextChanged(s: CharSequence?, start: Int, count: Int, end: Int) {
        if (s.isNullOrEmpty()){
            itemView.cCount1.visibility = View.GONE
        } else {
            itemView.cCount1.visibility = View.VISIBLE
        }
    }
    

    Reference for more details: https://developer.android.com/reference/android/view/View#setVisibility(int)