Home » Android » android – How to hide/show TextView from java

android – How to hide/show TextView from java

Posted by: admin June 15, 2020 Leave a comment

Questions:

I have TextView in one of my layout. I want keep it hide and only want make visible one time on button click, how can I do it ? My view is like below.
Thanks

        <TextView
            android:layout_marginBottom="16dp"
            android:layout_marginRight="8dp"
            android:id="@+id/textAuthorSign"
            android:layout_gravity="right"
            android:text="- ABJ Abdul Kalam"
            android:textStyle="italic"
            android:textSize="16sp"
            android:typeface="serif"
            android:visibility="invisible"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

Thanks

How to&Answers:

I think you want a toggle (As stated by the question title)

XML File:

     <Button
         android:layout_height="wrap_content"
         android:layout_width="wrap_content"
         android:text="@string/self_destruct"
         android:onClick="hide" />

     <TextView
         android:layout_marginBottom="16dp"
         android:layout_marginRight="8dp"
         android:id="@+id/textAuthorSign"
         android:layout_gravity="right"
         android:text="- ABJ Abdul Kalam"
         android:textStyle="italic"
         android:textSize="16sp"
         android:visibility="invisible"
         android:typeface="serif"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content" />

Java:

 public void hide(View view) {

     TextView txtView = (TextView)findViewById(R.id.textAuthorSign);

     //Toggle
     if (txtView.getVisibility() == View.VISIBLE)
        txtView.setVisibility(View.INVISIBLE);
     else 
        txtView.setVisibility(View.VISIBLE);

     //If you want it only one time
     //txtView.setVisibility(View.VISIBLE);

 }

Answer:

First get the reference to the textView:

  TextView textView = (TextView)findViewById(R.id.textViewName);

Then

  textView.setVisibility(TextView.VISIBLE);

Answer:

You can use setVisibility method as of this example:

TextView tv = (TextView)findViewById(R.id.textAuthorSign);
tv.setVisibility(View.VISIBLE);

Will make your view visible and View.invisable will make your view invisible.

You can also do View.GONE and then the TextView won’t take any space on the layout…