你之前发表的内容非常正确:
- 仅通过指定颜色无法创建涟漪选择器
- 无法在API< 21中使用xml中的主题属性
我认为除了使用库或自己编写代码外,没有其他更好的方法。从代码中,您可以生成涟漪,使用主题属性等。
我曾经遇到过同样的问题,我只是编写了一堆类来轻松创建涟漪。例如,要获取主题颜色,我编写了一个简单的ColorStateList类:
public class ControlCheckedColorStateList extends ColorStateList {
public ControlCheckedColorStateList(Context context) {
super(new int[][]{
new int[]{android.R.attr.state_checked},
new int[]{}
}, new int[]{
getThemeColor(context, R.attr.colorPrimary),
getThemeColor(context, R.attr.colorControl)
});
}
public static int getThemeColor(Context context, int attr) {
Resources.Theme theme = context.getTheme();
TypedValue typedvalueattr = new TypedValue();
theme.resolveAttribute(attr, typedvalueattr, true);
return typedvalueattr.resourceId != 0 ? context.getResources().getColor(typedvalueattr.resourceId) : typedvalueattr.data;
}
}
然后我添加了涟漪颜色和样式的属性。我还必须重写setBackground方法,以便为视图设置涟漪不会清除其背景。现在设置自定义颜色的涟漪就像这样简单:
<carbon.widget.Button
android:background="#ffffffff"
app:carbon_rippleColor="#40ff0000"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
大量的代码行,我认为在这里发布所有代码是不合理的。如果您愿意,可以打开我的库中的任何小部件类,并检查它是否符合您的要求。 您可以在
github 上找到我的代码。如果有任何问题,请随时提问。
selectableItemBackgroundBorderless
,因为我所需要的只是灰色背景(而selectableItemBackground
是蓝色)。但显然它并不是这样,所以寻找正确的属性需要一些努力。总而言之,在21版本以下,人们可以简单地创建自己的状态可绘制图案。 - Actine