Reputation: 330
Im trying to change (onClick) the background of an ImageView inside my GridView, but whem i click it, the selected row and another random one react to the click. Below is my code:
@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);
}
}
});
Any help is appreciated. Thanks! :]
Upvotes: 1
Views: 702
Reputation: 954
One way is to set a unique id for the ImageView(s) in java or xml which might be something like:
Java (multiple views being created with repeat of same code:
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 (multiple views in xml layout):
<!-- Copy and paste and new name for each and every view needed -->
android:id="@+id/id_name_here"
Now because every id is now unique the listener can pick the correct view.
EXAMPLE:
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);
}
There might be other code changes or additions needed as well perhaps such as the way that the views are created. But a unique id does keep each view separate allowing you to set or get of only the correct view and no other.
Upvotes: 1