How to grey out a button?

jul picture jul · Jan 5, 2012 · Viewed 139.7k times · Source

I have a button defined as shown below. When I want to disable it I use my_btn.setEnabled(false), but I would also like to grey it out. How can I do that?

Thanks

<Button android:id="@+id/buy_btn" style="@style/srp_button" />

style/srp_button

<style name="srp_button" parent="@android:style/Widget.Button">
    <item name="android:background">@drawable/btn_default</item>
    <item name="android:layout_width">wrap_content</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:textColor">#ffffff</item>
    <item name="android:textSize">14sp</item>
    <item name="android:typeface">serif</item>
    <item name="android:paddingLeft">30dp</item>
    <item name="android:paddingRight">30dp</item>
    <item name="android:paddingTop">5dp</item>
    <item name="android:paddingBottom">5dp</item>
</style>

drawable/btn_default.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@color/pink" />
    <corners android:radius="6dp" />
</shape>

Answer

Siavash picture Siavash · Nov 25, 2014

You could Also make it appear as disabled by setting the alpha (making it semi-transparent). This is especially useful if your button background is an image, and you don't want to create states for it.

button.setAlpha(.5f);
button.setClickable(false);

update: I wrote the above solution pre Kotlin and when I was a rookie. It's more of a "quick'n'dirty" solution, but I don't recommend it in a professional environment.

Today, if I wanted a generic solution that works on any button/view without having to create a state list, I would create a Kotlin extension.

fun View.disable() {
    getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY)
    setClickable(false)
}

In Java you can do something is similar with a static util function and you would just have to pass in the view as variable. It's not as clean but it works.