问题
I have this code and works for every version since API 14 but on Android 5.0 (Lollipop) isn't working correctly.
Below is the way how I want the buttons appear.
click of button1
buttonArrivals.getBackground().setAlpha(180);
buttonDepartures.getBackground().setAlpha(255);
click of button2
buttonArrivals.getBackground().setAlpha(255);
buttonDepartures.getBackground().setAlpha(180);
On Lollipop version the buttons appear with the same Alpha but I never set the same alpha. I just use the code above.
UPDATE 24/11/2014
Here is the xml of the buttons (AutoResizeButton extends Button)
br.com.timo.gru.util.AutoResizeButton
android:id="@+id/buttonArrivals"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:background="#00abbd"
android:drawableLeft="@drawable/icon_aviao_desemb"
android:drawablePadding="-5dp"
android:drawableStart="@drawable/icon_aviao_desemb"
android:gravity="center"
android:paddingEnd="0dp"
android:paddingLeft="2dp"
android:paddingRight="0dp"
android:text="@string/chegadas"
android:textColor="@android:color/white"
br.com.timo.gru.util.AutoResizeButton
android:id="@+id/buttonPartidas"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:background="#00abbd"
android:drawableLeft="@drawable/icon_aviao_partida"
android:drawablePadding="-5dp"
android:drawableStart="@drawable/icon_aviao_partida"
android:ellipsize="end"
android:gravity="center"
android:text="@string/partidas"
android:textColor="@android:color/white"
回答1:
Internally ColorState (used by ColorDrawable) is shared between these 2 buttons (optimization), so whenever you change alpha on one button's background - other button will get this change as well. You can try to to mutate background drawable before changing its alpha:
buttonArrivals.getBackground().mutate().setAlpha(180);
buttonDepartures.getBackground().mutate().setAlpha(255);
You can also read good explanation from Romain Guy on why this is happening: http://curious-creature.org/2009/05/02/drawable-mutations
However, it looks like you try to implement something which is easily achievable with Android selectors. You can specify different color for each button state (in your case selected/not selected), so in your code you just need to update state:
buttonArrivals.setSelected(true);
buttonDepartures.setSelected(false);
And selector would look like:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="#ff00abbd"
android:state_selected="true" >
</item>
<item android:color="#b400abbd"
android:state_selected="false">
</item>
</selector>
来源:https://stackoverflow.com/questions/27115181/button-with-getbackground-setalpha-on-version-5-lollipop-isnt-working-corre