Pages

Thursday, 30 June 2011

View visibility

How do I hide and show view controls in my app?
View controls (TextView, EditText, Button, Image, etc) all have a visibility property. This can be set to one of three values:
  • Visible - Displayed
  • Invisible - Hidden but space reserved
  • Gone - Hidden completely
The visibility can be defined in the layout XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <Button
     android:id="@+id/button1"
     android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:text="You can see me"
    android:visibility="visible" />
    <Button
     android:id="@+id/button2" android:dr
     android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:text="You cannot see me, but you can see where I am"
    android:visibility="invisible" />
    <Button
     android:id="@+id/button3"
     android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:text="You have no idea that I am here"
    android:visibility="gone" />
</LinearLayout>

For the LinearLayout above, the three buttons laid out horizontally with equal weights will be displayed as below. You can see the first, the space for the second, but not the third:



To set the visibility in code use the public constant available in the static View class:

Button button1 = (TextView)findViewById(R.id.button1);
button1.setVisibility(View.Visible);

You see?

0 comments:

Post a Comment