【问题标题】:ListView item deletion changes item heightsListView 项目删除更改项目高度
【发布时间】:2013-07-28 16:02:43
【问题描述】:

我有一个ListView,可以通过滑动删除其项目。当一个项目被滑动时,它的数据库行以及它在适配器数据集中的对象被删除,并且notifyDataSetChanged() 也被调用。问题是,这些项目有不同的高度——一个可以是单线,第二个可以有四线。所以当我在列表中有一些项目时,让我们说:

1.一行

2.两行

3.三行

4.一行

第二个被删除,第三个被删除(如预期的那样),但被截断为两行。并且当第三个被删除时,第四个的高度会增加以匹配被删除的项。

我找到了解决这个问题的方法,但它可能是错误的 - 即使 convertView 不为空,它也会创建一个新视图。

我想知道这是否可以通过另一种回收友好的方式实现。

当前适配器代码:

public class CounterItemAdapter extends BaseAdapter{
    private Activity activity;
    private ArrayList<CounterItem> data;
    private SQLiteOpenHelper helper;
    private static LayoutInflater inflater = null;

    public CounterItemAdapter(Activity activity, ArrayList<CounterItem> data, SQLiteOpenHelper helper) {
        this.activity = activity;
        this.data = data;
        this.helper = helper;
        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return data.size();
    }


    @Override
    public CounterItem getItem(int position) {
        return data.get(position);
    }
    @Override
    public long getItemId(int position) {
        return getItem(position).getId();
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;
        //if(convertView == null)
            view = inflater.inflate(R.layout.counter_list_item, null);
        TextView nameView = (TextView)view.findViewById(R.id.nameView);

        //other, unrelated views were here

        final CounterItem counterItem;
        counterItem = getItem(position);

        nameView.setText(counterItem.getName());

        return view;
    }
}

【问题讨论】:

    标签: java android listview adapter


    【解决方案1】:

    好的,我找到了解决办法。

    添加int lastValidPosition = -1; 在适配器中,然后是adapter.lastValidPosition = position-1 在删除回调方法中,在adapter.notifyDataSetChanged();之前 ,并且在适配器的getView() 方法中我已更改

    //if(convertView == null)
        view = inflater.inflate(R.layout.counter_list_item, null);
    

    if(lastValidPosition < position | convertView == null){
        view = inflater.inflate(R.layout.counter_list_item, null);
        lastValidPosition = position;
    }
    

    而且效果很好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-22
      相关资源
      最近更新 更多