当用户在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;
    }
}
有帮助吗?

解决方案

使用statelistable可用于state_selected的定义项目。

<?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>

This way, when the list item is selected it will use that "selected" graphic automatically.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top