gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 02:38:55 25 4
gpt4 key购买 nike

我试图更改 (onClick) 我的 GridView 中 ImageView 的背景,但是当我单击它时,选定的行和另一个随机的行对单击使用react。下面是我的代码:

@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);
}
}
});

感谢任何帮助。谢谢! :]

最佳答案

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

Java(通过重复相同的代码创建多个 View :

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 布局中的多个 View ):

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

现在因为每个 id 现在都是唯一的,听众可以选择正确的 View 。

示例:

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);
}

可能还需要更改或添加其他代码,例如创建 View 的方式。但是唯一的 ID 确实使每个 View 保持独立,从而允许您仅设置或获取正确的 View ,而不能设置其他 View 。

关于Android:响应项目点击的多个gridView行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26070701/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com