【发布时间】:2017-05-23 01:18:22
【问题描述】:
我创建了一个放入 ListView 的自定义列表项。这些项目是可单击的(单选和多选),一旦单击,我希望它们更改颜色而不会失去漂亮的 Material 波纹效果。
这就是切换后只改变颜色的静态方式:
public class CustomListItem extends LinearLayout implements Checkable {
public CustomListItem(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomListItem(Context context) {
super(context);
}
private boolean checked = false;
private TextView textView;
@Override
protected void onFinishInflate() {
super.onFinishInflate();
textView = (TextView) findViewById(R.id.listViewText);
}
@Override
public void setChecked(boolean checked) {
this.checked = checked;
int color = checked ? R.color.colorAccent : R.color.appWhite;
textView.setBackgroundColor(ContextCompat.getColor(getContext(), color));
}
@Override
public boolean isChecked() {
return checked;
}
@Override
public void toggle() {
setChecked(!checked);
}
}
我还创建了自己的波纹可绘制对象,这样我就可以在不失去波纹效果的情况下更改颜色 - 但是这样项目的颜色保持不变/不改变。
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="?attr/colorControlHighlight">
<item android:drawable="?attr/colorAccent" />
</ripple>
简而言之:我希望我的列表项在单击时从背景颜色 x 变为 y,然后从 y 变为 x,但仍会对它们产生涟漪效应。
非常感谢帮助,谢谢!
【问题讨论】:
-
你试过在xml中设置:
android:foreground="?android:attr/selectableItemBackground"吗? -
太棒了!好像是我要找的东西-谢谢。 @MarkKeen
-
请注意,
android:foreground仅在以 Marshmallow (api 23) 开头的任意Views 上可用。在此之前,它仅在FrameLayout上可用。