Android:响应项目点击的多个gridView行

时间:2014-09-27 02:31:22

标签: android listview gridview android-listview android-gridview

我试图在GridView中更改(onClick)ImageView的背景,但是当我点击它时,所选行和另一个随机的行对点击作出反应。以下是我的代码:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    final ViewHolder holder;
    final int index = position;

    if (convertView == null) {
        convertView = inflater.inflate(R.layout.item_grid_galeria_modelo, parent, false);

        holder = new ViewHolder();
        holder.imageView = (ImageView) convertView.findViewById(R.id.image);
        holder.favoriteStar = (ImageView) convertView.findViewById(R.id.img_fav_star);

        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }
    holder.favoriteStar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!holder.isFavorited) {
                holder.isFavorited = true;
                holder.favoriteStar.setImageResource(R.drawable.ic_star);
            } else { 
                holder.isFavorited = false;
                holder.favoriteStar.setImageResource(R.drawable.ic_star_grey);
            }
        }
    });

感谢任何帮助。谢谢! :

1 个答案:

答案 0 :(得分:1)

一种方法是为java或xml中的ImageView设置一个唯一的id,可能类似于:

Java(重复使用相同代码创建多个视图:

ViewHolder vh;
ImageView iv;
View vi;
int location = 0;

vi = view;
vh = new ViewHolder();

// Use to get the current ImageView being worked on.
vh.iv = (ImageView) vi.findViewById(R.id.image);

// Use to set new id for the ImageView currently being worked on.
vh.iv.setId(location++);

xml(xml布局中的多个视图):

<!-- Copy and paste and new name for each and every view needed --> 
android:id="@+id/id_name_here"

现在因为每个 id现在都是唯一的,所以侦听器可以选择正确的视图。

实施例

public void clickListener(View view) {
final int id = view.getId();

// Can now get the unique id of the exact ImageView that was clicked
ImageView iv = (ImageView) findViewById(id);

// Will now set new image for and only for the correct ImageView that was clicked.
iv.setImageResource(R.drawable.ic_star);
}

可能还需要其他代码更改或添加,例如创建视图的方式。但是一个唯一的ID确实将每个视图分开,允许您只设置或获取正确的视图,而不是其他视图。