Matt - sanemat
Matt - sanemat

Reputation: 5618

Toggling a TextView visibility on click

I want to toggle textView on click. enter image description here

val targetView = findViewById<TextView>(R.id.targetText)
targetView.text = 'example'
targetView.setOnClickListener {
  if (it.visibility == View.VISIBLE) {
    it.visibility = View.INVISIBLE
  } else {
    it.visibility = View.VISIBLE
  }
}

But once I clicked and visibility of text was changed to invisible, then I can not click this again.

Upvotes: 0

Views: 97

Answers (2)

Nikos Hidalgo
Nikos Hidalgo

Reputation: 3756

Store the text of the textview in a temporary string. Instead of toggling the visibility, set the text to null and then back to what it was using the temp variable.

String final tempText = "your text"

then

targetView.setOnClickListener(new View.OnClickListener) {
    @Override
    public void onClick(View view){
        if (view.getText() == null) {
            view.setText(tempText);
        } else {
            view.setText("   ");   
        }
     });
}

just make sure your textview on the layout properties has a set minWidth and not wrap_content as it will disappear when you set the text to null

Upvotes: 0

SuuSoJeat
SuuSoJeat

Reputation: 1136

Suggestion: How about creating a view behind the text and make use of the view for toggle triggering instead of text.

i.e. onViewClicked { toggleTextVisibility() }

Upvotes: 1

Related Questions