恢复listview项的x偏移量

时间:2014-05-12 12:02:21

标签: android

我正在实施一个BaseAdapter,我有一个列表项的TranslateAnimation。

问题在于向下滚动时其他视图具有相同的偏移量。

以下是getView()方法的实现:

        @Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder viewHolder;
    if (convertView == null) {
            //initialization code
            convertView.setTag(viewHolder);
    } else {
         viewHolder =(ViewHolder) convertView.getTag();
    }

        Animation animation;
        switch (item.getAnimationDirection()) {
        case AnimationDirection.HIDE:
            animation = new TranslateAnimation(itemOffset, 0, 0, 0);
            animation.setDuration(200);
            animation.setFillAfter(true);
            viewHolder.layoutToAnimate.setAnimation(animation);
            item.setAnimationDirection(AnimationDirection.HIDDEN);
            break;
        case AnimationDirection.REVEAL:
            itemOffset = viewHolder.remove.getWidth() + 20;
            animation = new TranslateAnimation(0, itemOffset, 0, 0);
            animation.setDuration(200);
            animation.setFillAfter(true);
            viewHolder.layoutToAnimate.setAnimation(animation);
            item.setAnimationDirection(AnimationDirection.SHOWING);
            break;
        }

        viewHolder.remove.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (item.getAnimationDirection() == AnimationDirection.HIDDEN) {
                    item.setAnimationDirection(AnimationDirection.REVEAL);
                    notifyDataSetChanged();
                }
            }
        });
        convertView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (item.getAnimationDirection() == AnimationDirection.SHOWING) {
                    item.setAnimationDirection(AnimationDirection.HIDE);
                    notifyDataSetChanged();
                }
            }
        });
        return convertView;
  }

我的问题是:

如何为每个View项保留ListView偏移状态?

3 个答案:

答案 0 :(得分:4)

Android框架提供了保留和恢复视图属性的钩子,因此您需要做的就是确保视图代码实现onSaveInstanceState()onRestoreInstanceState(Parcelable state),并在调用时为其子代调用相同的内容视图并调用父类的方法,例如super.onSaveInstanceState()

我发布了一个答案here,用于回答有关保留ListView中使用的数据的问题,还讨论了如何保留其他视图属性,例如评论中的滚动位置。

答案 1 :(得分:1)

为此使用Map<Integer, Integer>。像

这样的东西
map.put(position, offset);

int offset = map.get(position);

每次拨打getView时,请不要忘记设置此

答案 2 :(得分:0)

我遇到了类似的问题,但是我的颜色是并且有2个listview并排放置。我将红色设置为列表中触摸另一个列表中相同位置的项目。突出显示了正确的条目,但列表中的另一个项目也处于任意位置。我解决它的方法是使用if-else语句(我之前只使用过)。我在getview()中的代码是这样的:

if(position == highLightPosition){
holder.layout.setBackgroundColor(getResources().getColor(R.color.high_red));
}else{
//I set default color here that solved my problem
holder.layout.setBackgroundColor(getResources().getColor(R.color.white));
}

尝试这样的事情,我知道开关,如果看起来一样,但这对我有用。