Android如何更改GridView高亮颜色?

4
如何更改GridView中ImageView的高亮颜色。
我尝试过以下方法:
 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(width, height));
        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
        imageView.setBackgroundResource(R.drawable.menu_beh);
     //   imageView.setPadding(8, 8, 8, 8);
    } else {
        imageView = (ImageView) convertView;
    }

    String s=(String)HiveApp.mgd[position].posters[2].image.url;
 //   imageView.setImageDrawable(getPicture(items[position]));
   HiveApp.id.download(s, imageView); 


  //     id.DisplayImage(s, imageView);

    return imageView;
}
2个回答

13

我自己解决了,你应该将这个添加到你的布局XML中

 android:listSelector="@drawable/panel_picture_frame_background"

而不是这个

imageView.setBackgroundResource(R.color.gridview_highlight_selector);
感谢。

我也试过了,上面的选项崩溃了。 - Chris Barry

3
将以下内容添加到drawable文件夹中的imageview_highlight_selector.xml文件中,然后调用imageView.setBackgroundResource(R.drawable.gridview_highlight_selector);
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
 <item android:state_pressed="true"
       android:drawable="@drawable/highlight_bg" /> <!-- pressed -->
 <item android:drawable="@drawable/normal_bg" /> <!-- default -->
</selector>

我建议您在xml文件中定义gridview项目,然后从Java代码中填充该xml,这样会更整洁。
编辑:
如果您只想使用颜色而不是drawable,可以在res文件夹中添加一个color子文件夹,并将以下内容添加为gridview_highlight_selector.xml到color文件夹中,并在您的代码中调用imageView.setBackgroundResource(R.color.gridview_highlight_selector)。
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:color="#ffff" />
    <item android:color="#ff3697de" />
</selector>

1
谢谢您的回答,但这改变了项目背景的状态,橙色高亮仍然存在... - Vervatovskis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接