How to grey out a button?
All given answers work fine, but I remember learning that using setAlpha can be a bad idea performance wise (more info here). So creating a StateListDrawable is a better idea to manage disabled state of buttons. Here's how:
Create a XML btn_blue.xml in res/drawable folder:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Disable background -->
<item android:state_enabled="false"
android:color="@color/md_blue_200"/>
<!-- Enabled background -->
<item android:color="@color/md_blue_500"/>
</selector>
Create a button style in res/values/styles.xml
<style name="BlueButton" parent="ThemeOverlay.AppCompat">
<item name="colorButtonNormal">@drawable/btn_blue</item>
<item name="android:textColor">@color/md_white_1000</item>
</style>
Then apply this style to your button:
<Button
android:id="@+id/my_disabled_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/BlueButton"/>
Now when you call btnBlue.setEnabled(true)
OR btnBlue.setEnabled(false)
the state colors will automatically switch.
You have to provide 3 or 4 states in your btn_defaut.xml
as a selector.
- Pressed state
- Default state
- Focus state
- Enabled state (Disable state with false indication; see comments)
You will provide effect and background for the states accordingly.
Here is a detailed discussion: Standard Android Button with a different color
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.
The most easy solution is to set color filter to the background image of a button as I saw here
You can do as follow:
if ('need to set button disable')
button.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
else
button.getBackground().setColorFilter(null);
Hope I helped someone...