Android:如何在长按列表项时实现发光效果?

10

使用默认选择器,长按列表项会导致其背景在两种颜色之间转换。

将选择器替换为下面的选择器将删除这种效果。根据这个问题,我需要一种动画来复制它。我如何在xml中实现它?

<?xml version="1.0" encoding="utf-8"?>
<selector
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_pressed="true">
        <shape>
            <solid
                android:color="@color/state_pressed" />
        </shape>
    </item>
    <item
        android:state_focused="true">
        <shape>
            <solid
                android:color="@color/state_focused" />
        </shape>
    </item>
    <item>
        <shape>
            <solid
                android:color="@color/state_idle_grey" />
        </shape>
    </item>
</selector>
1个回答

9
这是来自list_selector_background的代码:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:state_window_focused="false" android:drawable="@android:color/transparent" />
        <!--
                Even though these two point to the same resource, have two states so
                the drawable will invalidate itself when coming out of pressed state.
        -->
        <item android:state_focused="true" android:state_enabled="false"
                android:state_pressed="true"     android:drawable="@drawable/list_selector_background_disabled" />
        <item android:state_focused="true" android:state_enabled="false"
                android:drawable="@drawable/list_selector_background_disabled" />
        <item android:state_focused="true" android:state_pressed="true"
                android:drawable="@drawable/list_selector_background_transition" />
        <item android:state_focused="false" android:state_pressed="true"
                android:drawable="@drawable/list_selector_background_transition" />
        <item android:state_focused="true"
                android:drawable="@+drawable/list_selector_background_focus" />
</selector>

在网上找到了相关资料

对于长按点击,它使用了这个过渡效果:

<transition xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/list_selector_background_pressed"  />
    <item android:drawable="@drawable/list_selector_background_longpress"  />
</transition>

在网上也找到了这个。没有动画效果。请记住保持状态的顺序不变,或者如果您交换它们,请至少考虑一下,顺序很重要。

个人而言,我喜欢事物以标准方式运作,所以我会使用标准列表选择器。

祝好, Stéphane


2
不起作用,还有什么想法吗?我按照你说的应用了过渡效果,你的意思是针对“list_selector_background_transition.xml”文件,我们要添加你在第二个代码块中给出的过渡效果吗?我完全按照你说的做了,但只有一个颜色改变了,即只应用了“list_selector_background_pressed”。 - coderVishal
@coderVishal,你使用RecyclerView吗?这个解决方案仅适用于使用AbsListView的子类(例如,ListView)。它检查项目背景是否具有TransitionDrawable并启动动画。不幸的是,RecyclerView没有这种情况,你必须发明一些机制来自己启动动画。 - Malcolm

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接