from:http://blog.sina.com.cn/s/blog_4b650d650100nq75.html

刚刚学习Android的时候,GridView上元素的背景把我搞得很狼狈,那个背景的大小难以控制,导致一个元素背景经常会覆盖到相邻的元素.我费了好大力气才把GridView调整好,但是元素的背景依然没有好的办法去调整.

    使用<selector>风格化Android的GridView元素背景
    我所说的元素背景就是上面图片中Car Home图标后面的桔红色的方块.

    今天看了一段代码,是SDK/Sample/HOME项目,大家可以研究一下.

    在布局文件home.xml中有下面的代码:

    <GridView android:id="@+id/all_apps"
        android:background="@drawable/application_background"
        android:persistentDrawingCache="animation|scrolling"
        android:alwaysDrawnWithCache="true"
        android:scrollbars="none"
        android:drawSelectorOnTop="false"
        android:listSelector="@drawable/grid_selector"
        android:numColumns="auto_fit"
        android:columnWidth="78dp"
        android:stretchMode="spacingWidth"
        android:layout_weight="1.0"
        android:layout_height="0dip"
        android:layout_width="match_parent"
        android:stackFromBottom="true"
        android:visibility="invisible" 
    />
    在GridView属性中注意上面绿色的那一行.它指定了元素的背景布局文件为dwawable目录下面的grid_selector.xml文件.打开grid_selector.xml文件,有下面的描述:

    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:state_pressed="true" 

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

             android:drawable="@drawable/focused_application_background_static" />
        <item android:state_window_focused="true" 

              android:drawable="@drawable/focused_application_background_static" />
    </selector>

    在此文件中,三个<item>分别指定了在点击图标,聚焦,失焦的情况下使用的元素背景

    其中,在dwawable-hdpi目录下的pressed_application_background_static.png文件显示为:

        使用<selector>风格化Android的GridView元素背景

    在dwawable-hdpi目录下的focused_application_background_static文件显示为: 

      使用<selector>风格化Android的GridView元素背景
    这就是我们点击图标元素和滚动图标元素时元素后面的背景.我们通过这样的方法就可以改变其大小,形状以及颜色了,这会使你的GridView制作得更漂亮.