【问题标题】:Update only clicked image on GridView仅更新 GridView 上单击的图像
【发布时间】:2015-07-07 09:23:59
【问题描述】:

我有一个使用 ImageView 元素的自定义适配器的 GridView。我想更改 ImageView onItemClick 并且我有一些点击条件。如果单击的项目可用,我会更改图像。但是当我更改项目的图像资源时,我必须通过 adapter.notifyDataSetChanged(); 更新整个 GridView。我的 GridView 有 100 个元素,所以更新它们都会花费我半秒的延迟,这很令人不安。如何只更新我已更改的元素?

这是我在适配器中的 getView() 方法。

  public View getView(final int position, View convertView, ViewGroup parent) {
    Point point;
    View v = null;
    point=items.get(position); 
    int resId;
    resId=point.getBackground();
    v = inflater.inflate(R.layout.item, null);
    ImageView tv = (ImageView) v.findViewById(R.id.image_button);
    tv.setImageResource(resId);
    return v;
}

这是我在 Point 对象上的 getBackground() 方法

public int getBackground(){
    int backId=(R.drawable.button_initial);
    if(isFilled){
        backId=(R.drawable.button_clicked);
    }
    else if(isAvailable){
        backId=(R.drawable.button_green);
    }
    return backId;
}

提前致谢。

【问题讨论】:

  • 顺便说一句:ackId=(R.drawable.button_clicked) 括号是干什么用的?
  • 坏习惯。我对所有我不知道为什么的东西都使用括号

标签: android gridview imageview custom-adapter


【解决方案1】:

您应该更新项目列表中的点,然后调用 notifyDataSetChanged();

最好在 Activity 中这样做......就像那样

List<Point> points = new ArrayLIst<Point>;
Adapter adapter = new Adapter(points);

    gridView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
      @Override
      public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        Point p = items.get(position);
        p.setBackground(..);
        adapter.notifyDataSetChanged();
      }

      @Override public void onNothingSelected(AdapterView<?> parent) {

      }
    });

【讨论】:

  • 这就是我正在做的事情。我在 Activity 中设置值并调用 notifyDataSetChanged();。但是当我调用该方法时,它会更新整个 GridView 并导致延迟。所以我不想使用 notifyDataSetChanged();这就是问题
  • 这不是推荐的方式,但您可以在为视图充气时将点击监听器放在视图上。 v = inflater.inflate(R.layout.item, null);您还应该考虑使用 ViewHolder 模式。
猜你喜欢
  • 2017-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-10
相关资源
最近更新 更多