why custom state won't work with compound drawable?
Posted
by
schwiz
on Stack Overflow
See other posts from Stack Overflow
or by schwiz
Published on 2010-12-24T08:11:23Z
Indexed on
2010/12/24
11:54 UTC
Read the original article
Hit count: 309
Hello I am trying to make a password registration widget that will show a little checkbox in the textbox when both password boxes match. I decided to go about this by extending EditText
to implement a valid and an empty state and then just use a state-list drawable to handle everything else.
I followed the same method that the CompoundButton
uses to add a custom state and everything seems to be right but the image will never change no matter what the state is (custom state or even state_focused etc)
Is there some reason that the compound drawables of a TextView
wouldn't work as a state-list drawable? Or, am I doing something wrong?
Here is attrs.xml
<resources>
<declare-styleable name="ValidyState">
<attr name="state_valid" format="boolean"/>
<attr name="state_has_text" format="boolean"/>
</declare-styleable>
</resources>
my selector
<selector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res/com.schwiz.test">
<item android:drawable="@drawable/emptyspace"
app:state_has_text="false"/>
<item android:drawable="@drawable/ic_valid"
app:state_valid="true"
app:state_has_text="true"/>
<item android:drawable="@drawable/ic_invalid"
app:state_valid="false"
app:state_has_text="true"/>
</selector>
and in my overridden EditText
class
private static final int[] VALID_STATE_SET = {
R.attr.state_valid
};
private static final int[] HASTEXT_STATE_SET = {
R.attr.state_has_text
};
...
private void refreshDrawables(){
Drawable[] drawables = getCompoundDrawables();
for(int i = 0; i < drawables.length; i++){
if(drawables[i] != null) {
drawables[i].setState(getDrawableState());
}
}
invalidate();
}
@Override
protected void drawableStateChanged() {
super.drawableStateChanged();
refreshDrawables();
}
@Override
protected int[] onCreateDrawableState(int extraSpace) {
final int[] drawableState = super.onCreateDrawableState(extraSpace + 2);
if(hasText){
mergeDrawableStates(drawableState, HASTEXT_STATE_SET);
}
if(isValid){
mergeDrawableStates(drawableState, VALID_STATE_SET);
}
return drawableState;
}
© Stack Overflow or respective owner