Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally displaying button

I know how to enable/disable a button defined in a layout XML after finding it:

  testBtn = (Button)findViewById(R.id.test);

But other than conditionally loading layouts, is there a way to tell in my code "Use that layout XML, but don't load the button defined there"?

like image 301
an00b Avatar asked Dec 13 '22 14:12

an00b


1 Answers

To set a View's visibility in Xml, use the android:visibility attribute.

The following sets the button visibility to gone. When set to gone Android will not show the button and not include it's size during layout calculation.

<Button android:id="@+id/mybutton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello" 
            android:visibility="gone"/>

Setting android:visibility="invisible" will not show the button, but include it during layout calculation.

<Button android:id="@+id/mybutton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello" 
            android:visibility="invisible"/>

To programmatically show the button in code you call the setVisibility() method.

Button btn = (Button)findViewById(R.id.thebuttonid);
btn.setVisibility(View.VISIBLE); //View.GONE, View.INVISIBLE are available too.
like image 52
Ryan Reeves Avatar answered Jan 15 '23 13:01

Ryan Reeves