How to Disable a Button in Android

Just like any View component in android, you can disable a button in android by simply setting android button enable  attribute to false android:enabled="false".

The default value of android:enableis true.

Disable Android Button in XML Layout

activity_main.xml

<Button
  android:id="@+id/button"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:background="@color/colorAccent"
  android:textColor="@color/colorWhite"
  android:text="Button Disabled"
  android:enabled="false"
  android:textStyle="bold"
  android:textSize="15sp"/>

Disable Android Button Programmatically

Imagine that we did not add android:enable="false"in the XML layout. we can achieve the same result by using the Button class setEnable()method as shown below.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/root_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="24dp"
    android:gravity="center"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorAccent"
        android:textColor="@color/colorWhite"
        android:text="Button Disabled"
        android:textStyle="bold"
        android:textSize="15sp"/>

</androidx.appcompat.widget.LinearLayoutCompat>

MainActvity.java

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button buttonEffect = (Button)findViewById(R.id.button);
        buttonEffect.setEnabled(false);
        buttonEffect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "Button disabled", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

As you can seen in the above code, once the button is disabled, the click event does not work.

Not that there is a difference between disabled view and hiding a view using the view visibility.

android disable button

If you have any questions or suggestions kindly use the comment box or you can contact us directly through our contact page below.

 

Add a Comment