Make a button invisible or gone in an Android Application

In this post I will show you how to make button visible and invisible or gone. First let’s create three¬† buttons in our application and make them visible.
This is the layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <Button
        android:text="Button One"
        android:id="@+id/Button01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </Button>
    <Button
        android:text="Button Two"
        android:id="@+id/Button02"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </Button>
    <Button
        android:text="Button Three"
        android:id="@+id/Button03"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </Button>
</LinearLayout>

Setting buttons to be visible:

package com.lardev.myButton;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;

public class Main extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button myButton1 = (Button) findViewById(R.id.Button01);
        myButton1.setVisibility(0);
        Button myButton2 = (Button) findViewById(R.id.Button02);
        myButton2.setVisibility(0);
        Button myButton3 = (Button) findViewById(R.id.Button03);
        myButton3.setVisibility(0);
    }
}

And the result is:

Now go to line 17 and change parameter from 0 to 4 and second button will be invisible when you save and start your application again, but it still takes up space in layout.

If we want to make button invisible and doesn’t take any space in the layout, then we must change parameter 8 for setVisibility method.

package com.lardev.myButton;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;

public class Main extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button myButton1 = (Button) findViewById(R.id.Button01);
        myButton1.setVisibility(0);
        Button myButton2 = (Button) findViewById(R.id.Button02);
        myButton2.setVisibility(8);
        Button myButton3 = (Button) findViewById(R.id.Button03);
        myButton3.setVisibility(0);
    }
}

And now button two is invisible and gone.Here you can see the result:

And that’s all for now, good luck

Posted in Android at February 28th, 2011. 1 Comment.