【问题标题】:Ripple effect on ListView itemsListView 项目上的涟漪效应
【发布时间】: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 上可用。

标签: android listview ripple


【解决方案1】:

我知道您已经找到了解决方案,但这是昨天对我有用的方法:

您不需要定义自己的波纹可绘制对象。只需在您的父 ListView 上执行此操作:

<ListView
    ...
    android:drawSelectorOnTop="true"/>

这将为您处理涟漪效应,因此您只需要在单击项目时更新自定义列表项的颜色(您已经在这样做)。

【讨论】:

    【解决方案2】:

    尝试使用selectableItemBackground 属性。

    android:background="?android:attr/selectableItemBackground"
    android:clickable="true"
    android:focusable="true"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-25
      • 2015-08-19
      相关资源
      最近更新 更多