0

我想更改 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);
}

但我想更改它而无需单击。

4

2 回答 2

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

希望这可以帮助

于 2013-03-24T21:52:50.367 回答
0

您可以为 中的每个位置View添加一个孩子。然后设置整个项目的背景。ImageViewgetView()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" />
于 2013-03-24T21:15:02.010 回答