问题
I'm attempting to tint a Drawable
using DrawableCompat
but for some reason the Drawable
is not always respecting state_pressed
I have a ColorStateList
which looks like:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/black" android:state_pressed="true" />
<item android:color="@color/yellow" android:state_checked="true" />
<item android:color="@color/gray" />
</selector>
I set this on my Drawable
like so
myButton = (ToggleButton) findViewById(R.id.button);
Drawable drawable = DrawableCompat.wrap(myButton.getBackground());
DrawableCompat.setTintList(drawable, getResources().getColorStateList(R.color.color_list));
myButton.setBackgroundDrawable(DrawableCompat.unwrap(drawable));
myButton.setOnClickListener(this);
The ToggleButton
xml is as follows:
<ToggleButton
android:id="@+id/my_button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1.0"
style="?attr/borderlessButtonStyle"
android:background="@drawable/my_nine_patch"
android:clickable="true"
android:enabled="true"
android:focusable="true"
android:textOff="@string/none"
android:textOn="@string/none" />
What I'd expect is that when I press down on the button it changes to black and then when I unpress the button it is either yellow or gray as appropriate.
However, initially nothing happens. When I press the button quickly a number of times it cycles through black, yellow, and gray seemingly at random.
Interestingly Even if I call setPressed(true) on the ToggleButton
, it is still not being changed to black.
Am I doing something wrong with my selector? Do I need to do some sort of magic incantation with ToggleButton
to make it work?
来源:https://stackoverflow.com/questions/34293880/android-togglebutton-not-reliably-receiving-state-pressed