Android ListView选择动画

标签 android android-listview android-animation listview-adapter

当用户在 ListView 中选择一个元素时,如何设置动画?

我正在制作自己的 ListView 适配器,以将偶数行设置为粉红色背景,将奇数行设置为紫色背景。唯一的问题是我不确定如何为用户点击(“触摸”)元素设置动画。

我想实现 OnTouchListener 并在选中时将背景更改为绿色,但由于实现了 OnTouchListener,行内的按钮可能不再起作用。这是真的吗?

代码:

public class MyAdapter extends BaseAdapter {

    public View getView(int position, View convertView, ViewGroup parent) {
        // position is the element's id to use
        // convertView is either null -> create a new view for this element!
        //                or not null -> re-use this given view for element!
        // parent is the listview all the elements are in    

        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.your_layout, null);

            // here you must do whatever is needed to populate the elements of your
            // list element layout
            ...
        } else {
            // re-use the given convert view

            // here you must set all the elements to the required values
        }

        // your drawable here for this element 
        convertView.setBackground(...);

        // maybe here's more to do with the view
        return convertView;
    }
}

最佳答案

使用带有 state_selected 定义项的 StateListDrawable。

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="true" android:drawable="@drawable/selected" />
    ...Other States...
    <item android:drawable="@drawable/normal" />
</selector>

这样,当列表项被选中时,它会自动使用“选中”的图形。

关于Android ListView选择动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4504619/

相关文章:

java - 为什么我的 SQL create 语句导致我的应用程序崩溃?

android - 如何使用 xml 或使用 java 更改按钮的形状?

java - 如何从菜单按键调用上下文菜单?

android - 使 ListView 移动到最后一项位置

java - 在 ValueAnimator 中使用 Float 值会导致异常

android - Android 中的 Activity 转换动画

android - 如何删除我的编辑文本上的 ` frequently used email ` toast?

android - 如何获取自定义适配器 ListView 中的所有项目?

android - 打开应用程序来电或去电断开后

android - 如何在主题更改时制作循环显示效果? (就像在 Telegram 或 VK 中一样)