2013-03-24 71 views
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); 
} 

,但我想改变它没有一个点击。

回答

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

希望这有助于

+0

谢谢!工作:) – Dennis 2013-03-25 10:30:35

0

您可以用ImageView孩子为getView()中的每个位置充气View。然后设置整个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" /> 
+0

我不能正确理解你。你能举个例子吗?对不起,但我是android开发新手。 – Dennis 2013-03-24 21:23:17

+0

我编辑了我原来的答案。它未经测试。 – wufufufu 2013-03-24 21:41:42