您的位置:首页 > 移动开发 > Android开发

Android开发:自定义GridView的子项在被选中、获取焦点、按下时的背景

2013-08-21 13:58 369 查看
去年的一个项目中需要用到标题中所提到的功能,这是个电视上的相册类android应用,使用遥控器的方向键进行操作,当GridView的子项被选中的时候其背景需要改变,当未被选中的时候,恢复原样。

实现方案是这样的:在GridView的Adapter中,自定义getView方法,在其中加载自定义的布局文件,找到需要设置背景的控件,在我的项目中是imageView,如下:

public View getView(int position, View convertView, ViewGroup parent) {

LayoutInflater laly=	LayoutInflater.from(MainActivity.this);
if (convertView == null)
{
convertView = laly.inflate(R.layout.item, null);
}
ImageView imageView = (ImageView) convertView.findViewById(R.id.myimg);
imageView.setImageResource(imgIds[position]);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setBackgroundResource(R.drawable.myselector);//关键点
TextView  textView = (TextView) convertView.findViewById(R.id.myimgTxt);
textView.setText("picture :"+position);

return convertView;

}


其中的R.drawable.myselector即为关键的部分,在其中设置被选中,按下等状态时的背景。

R.drawable.myselector是位于/res/drawable/目录下的myselector.xml,具体内容如下所示:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

<!-- When the window does not have focus. -->

<item android:drawable="@drawable/pic5"
android:state_selected="true"
android:state_window_focused="false"
/>

<item android:drawable="@drawable/pic6"
android:state_selected="false"
android:state_window_focused="false"
/>

<!-- When the window does have focus. -->

<item android:drawable="@drawable/pic5"
android:state_selected="true"
android:state_pressed="true"
/>

<item android:drawable="@drawable/pic5"
android:state_selected="true"
android:state_focused="true"
/>

<item android:drawable="@drawable/pic5"
android:state_selected="true"
/>

<item android:drawable="@drawable/pic6"
android:state_selected="false"
android:state_pressed="true"
/>

<item android:drawable="@drawable/pic6"
/>

</selector>


在上述所示的代码中更改相应的图片资源,即可实现对GridView子项背景的自定义。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐