我正在处理自定义按钮视图。但是当我尝试向GradientDrawable添加笔划时,我遇到了一些问题。
这是java代码:
protected void onFinishInflate() {
float[] radii = null;
if (mButtonCornerRadius > 0) {
radii = new float[8];
for (int i = 0; i < 8; i++) {
radii[i] = mButtonCornerRadius;
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
int[][] states = new int[][]{
new int[]{-android.R.attr.state_enabled}, // disabled
new int[]{android.R.attr.state_enabled},// disabled
new int[]{}
};
int[] colors = new int[]{
mButtonDisabledColor,
mButtonColor,
mButtonColor
};
ColorStateList colorStateList = new ColorStateList(states, colors);
mButton.setBackgroundResource(R.drawable.ripple_background);
RippleDrawable ripple = (RippleDrawable) mButton.getBackground();
GradientDrawable item = (GradientDrawable) ripple.findDrawableByLayerId(R.id.content);
item.setCornerRadii(radii);
item.setStroke((int) (mButtonStrokeWidth * getResources().getDisplayMetrics().density), mButtonStrokeColor);
DrawableCompat.setTintList(item.mutate(), colorStateList);
mButton.setBackgroundTintList(colorStateList);
mButton.setStateListAnimator(null);
} else {
GradientDrawable defaultItem = new GradientDrawable();
defaultItem.setDither(true);
defaultItem.setCornerRadius(mButtonCornerRadius * getResources().getDisplayMetrics().density);
defaultItem.setStroke((int) (mButtonStrokeWidth * getResources().getDisplayMetrics().density), mButtonStrokeColor);
defaultItem.setColor(mButtonColor);
GradientDrawable pressedItem = new GradientDrawable();
pressedItem.setDither(true);
pressedItem.setCornerRadius(mButtonCornerRadius * getResources().getDisplayMetrics().density);
pressedItem.setStroke((int) (mButtonStrokeWidth * getResources().getDisplayMetrics().density), mButtonStrokeColor);
pressedItem.setColor(mButtonHoverColor);
GradientDrawable disabledItem = new GradientDrawable();
disabledItem.setDither(true);
disabledItem.setCornerRadius(mButtonCornerRadius * getResources().getDisplayMetrics().density);
disabledItem.setStroke((int) (mButtonStrokeWidth * getResources().getDisplayMetrics().density), mButtonStrokeColor);
disabledItem.setColor(mButtonDisabledColor);
StateListDrawable stateListDrawable = new StateListDrawable();
stateListDrawable.addState(new int[]{android.R.attr.state_enabled, android.R.attr.state_pressed}, pressedItem);
stateListDrawable.addState(new int[]{-android.R.attr.state_enabled}, disabledItem);
stateListDrawable.addState(new int[]{android.R.attr.state_enabled}, defaultItem);
mButton.setBackgroundDrawable(stateListDrawable);
}
}
这是XML代码v21:
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="?android:attr/colorControlHighlight">
<item android:id="@+id/content">
<shape android:shape="rectangle">
<corners android:radius="7dp" />
<solid android:color="#660044" />
</shape>
</item>
</ripple>
一切正常(选择器,波纹,颜色等......),我无法在按钮上添加笔划。
我的错误在哪里?