Reputation: 2311
I want to change the background color for specific item in GridView (by position).
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
parent.getChildAt(1).setBackgroundColor(Color.RED);
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
It doesn't work.
If I use it in OnClickListener it works:
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
view.setBackgroundResource(android.R.drawable.btn_default);
}
but I want to change it without a click.
Upvotes: 0
Views: 4462
Reputation: 1438
Instead of parent.getChildAt(1).setBackgroundColor(Color.RED);
try
if(position==1){ // item's position that you want to change background color
[VIEW_YOU_WANT_TO_CHANGE_BACKGROUND].setBackgroundColor(Color.RED);
}else{
// Set other item's background color to default background color you want
[VIEW_YOU_WANT_TO_CHANGE_BACKGROUND].setBackgroundColor(Color.[WHAT_COLOR_YOU_WANT]);
}
Hope this helps
Upvotes: 1
Reputation: 83
You could inflate a View
with an ImageView
child for every position in getView()
. Then set the background of the entire View
item.
public View getView(int position, View convertView, ViewGroup parent) {
final ImageView imageView;
View v = null;
if (convertView == null) {
v = getLayoutInflater().inflate(R.layout.item_grid, parent, false);
imageView = (ImageView) v.findViewById(R.id.image);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
v.setBackground(R.drawable.whateverBackground)
} else {
v = convertView;
}
return v;
}
and have item_grid.xml
look like this
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/image"
android:layout_width="fill_parent"
android:layout_height="120dip"
android:adjustViewBounds="true"
android:contentDescription="@string/descr_image"
android:scaleType="centerCrop" />
Upvotes: 0