使用AnimationDrawable查看ListView中的回收

时间:2015-12-29 12:34:12

标签: android android-listview imageview android-animation animationdrawable

所以我有一个带有自定义适配器的ListView,允许我在项目点击上“选择”一个项目。 现在,列表的每一行都有一个ImageView,当选择了相应的项目时,其Drawable I将更改为“selected”图像。在我的Lollipop设备上正常工作。

我在列表适配器

的构造函数中构造Drawables
public DoubleRowSelectableArrayAdapter(Context context, int resource2, List<Recording> recordings) {
    super(context, resource2, recordings);

    idle = ContextCompat.getDrawable(context,R.drawable.idleicon);
    animation = (AnimationDrawable) ContextCompat.getDrawable(context, R.drawable.animation);
}

现在,正如您所看到的,“selected”项是一个AnimationDrawable,只要选择了一个视图,它就会播放(它是单选模式btw)。

视图在getView方法中更新

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    if (convertView == null) {
        LayoutInflater layoutInflater = LayoutInflater.from(getContext());
        convertView = layoutInflater.inflate(resource, null);
    }

    if (position == selection) {
        Log.d("getView", "selection = position");
        convertView.setSelected(true);
        convertView.setPressed(true);

        //get the imageview from the current row
        final ImageView pic = ((ImageView) convertView.findViewById(R.id.iconview));
        pic.setImageDrawable(animation);
    }
    else{
        Log.d("getView","else");
        convertView.setSelected(false);
        convertView.setPressed(false);

        //set idle icon
        ((ImageView) convertView.findViewById(R.id.iconview)).setImageDrawable(idle);
    }

我认为AnimationDrawable对所有列表项都有一个“全局”状态。因此,在构造函数中启动动画一次应该让动画始终为每个列表项播放。

我设法为每个项目播放动画,例如通过在构造函数中启动它或使用post()调用在getView方法中启动它。但是,我省略了部分代码,因为我想专注于一个稍微不同的东西。

以下是问题: 当我在播放动画时选择不同的列表项目(oneshot = false)时,如果新项目的位置低于旧项目的位置但是如果它超出列表中的旧项目位置,则将播放新选项目的动画。 所以,我选择了第一个项目。动画播放。选择第二项,动画播放。第三选,动画播放....第10项选中,动画播放。在另一个方向,这是行不通的。如果我播放了第10个项目的动画,并选择其中一个位置为1-9的项目,则动画将根本不播放。我必须等待正在运行的动画结束才能播放新动画。

如果每次调用getView时从资源中获取Drawable,这种行为都会改变 - 那么它工作得非常好。所以在getView

AnimationDrawable d = (AnimationDrawable) getContext().getResources().getDrawable(R.drawable.animation);
pic.setImageDrawable(d);
d.start(); //or by post() call, etc. -- however working.

我的猜测是,这与列表中的View回收有关。我应该怎么做才能在每次getView调用中保存drawable的(昂贵的?)实例化?

问题:为什么?如何正确设置动画?从每个新动画开始的资源中获取动画是否聪明(可能不是)?怎么做对了?

1 个答案:

答案 0 :(得分:1)

为什么? 每当播放动画时,在场景后面生成线程并将值应用于目标对象。此线程已同步,因此一次只能输入一个进程。因此,您为每个视图创建了单独的动画对象。

如何正确设置动画?我应该怎么做才能在每次getView调用中从资源中保存drawable的(昂贵的?)实例化?从每个新动画开始的资源中获取动画是否聪明(可能不是)?怎么做对了? 你正在做的就是你必须在每次getview()调用中创建animationDrawable。如果您想要为视图多次创建drawable(昂贵的任务),请将animationDrawable设置为标记并在每次getView调用时检索它,如果它为null则重新初始化。

如果不让我知道,我希望你得到答案。

相关问题