如何添加一个自定义的按钮状态

2024年11月18日 23:03
有1个网友回答
网友(1):









public FoodButton(Context context, AttributeSet attrs) {
super(context, attrs);
}

private static final int[] STATE_FRIED = {R.attr.state_fried};
private static final int[] STATE_BAKED = {R.attr.state_baked};

private boolean mIsFried = false;
private boolean mIsBaked = false;

public void setFried(boolean isFried) {mIsFried = isFried;}
public void setBaked(boolean isBaked) {mIsBaked = isBaked;}
Then override function "onCreateDrawableState":

@Override
protected int[] onCreateDrawableState(int extraSpace) {
final int[] drawableState = super.onCreateDrawableState(extraSpace + 2);
if (mIsFried) {
mergeDrawableStates(drawableState, STATE_FRIED);
}
if (mIsBaked) {
mergeDrawableStates(drawableState, STATE_BAKED);
}
return drawableState;
}

文件 "res/drawable/food_button.xml":

xmlns:app="http://schemas.android.com/apk/res/com.mydomain.mypackage">
app:state_baked="true"
app:state_fried="false"
android:drawable="@drawable/item_baked" />
app:state_baked="false"
app:state_fried="true"
android:drawable="@drawable/item_fried" />
app:state_baked="true"
app:state_fried="true"
android:drawable="@drawable/item_overcooked" />
app:state_baked="false"
app:state_fried="false"
android:drawable="@drawable/item_raw" />