我想更改GridView中特定项目的背景颜色(按位置)。
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;
}
它不起作用。
如果我在OnClickListener中使用它,它可以工作:
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
view.setBackgroundResource(android.R.drawable.btn_default);
}
但我想在没有点击的情况下进行更改。
答案 0 :(得分:1)
而不是parent.getChildAt(1).setBackgroundColor(Color.RED);
尝试
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]);
}
希望这有帮助
答案 1 :(得分:0)
对于View
中的每个位置,您可以为ImageView
孩子充气getView()
。然后设置整个View
项目的背景。
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;
}
让item_grid.xml
看起来像这样
<?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" />