I want to save app space with next idea. But I'm not sure if it possible.
I want to have selector:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/arrow_forward" android:state_enabled="true" />
<item android:drawable="@drawable/arrow_forward_disabled" android:state_enabled="false"/>
</selector>
Where arrow_forward
is png image and arrow_forward_disabled
is same image but with 70% opacity. I've tried to achieve it with layer-list
drawable but without success. Is there solution?
There is no way to apply opacity in xml. It is only possible using two images.
-
You are using PNG files, you will have to create 2 png's with different opacities.
1º PNG - Enable. 100% opacity.
2º PNG - Disabled. 70% opacity.
After this, you need to create a selector XML with 2 different states:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false" android:drawable="@drawable/btn_disabled" />
<item android:drawable="@drawable/btn_active" />
</selector>
You can also use shape buttons with different opacity using the alpha of ARGB (#AARRGGBB). Example: # 80FFFFFF (50% opacity) (Source)
Example:
Enabled:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<corners android:radius="20dp"/>
<solid android:color="#002aff" />
</shape>
Disabled (70% opacity: #b3002aff):
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<corners android:radius="20dp"/>
<solid android:color="#b3002aff" />
</shape>
If you are using a ShapeDrawable, instead of a PNG, you CAN effect the colors you are using to set different Opacities, I will outline some options:
This wouldn't work for opacity, but you could apply a color filter using the API that exists (this may be a variation on your effect based on color, but still wouldn't allow you to change the opacity of your PNG) Color Filter API
Create custom PNGs, each with the opacity you need
I think (like the other answers) that Option #3 is simplest, and will work the best.
Bottom line, you can't change the opacity of a PNG resource using XML, you could create a Drawable (maybe use it as a background for your PNG), and you would be able to change the opacity of that using it's color resource definition.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With