为Android GridView 设置行背景

经常有这样的需求,你的功能图标要像一个个物品,摆放在书架上,像这样:

我的思路比较简单,重载GridView,在他绘制子视图前,先把背景绘制完成

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public class RowGridView extends GridView {
    private static String NAMESPACE_ANDROID = "http://schemas.android.com/apk/res/android";
              
    private Bitmap rowBackground;
    private int rowBgHeight;
    private int columnNum;
              
    public RowGridView(Context context, AttributeSet attrs){
        super(context,attrs);
        //获得列数
        columnNum = attrs.getAttributeIntValue(NAMESPACE_ANDROID,"numColumns",3);
        //获取自定义属性
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.row_bg_grid_view);
        rowBgHeight = a.getDimensionPixelSize(R.styleable.row_bg_grid_view_row_bg_height,50);
        int row_bg_resource = a.getResourceId(R.styleable.row_bg_grid_view_row_background,-1);
        rowBackground = BitmapFactory.decodeResource(getResources(),row_bg_resource);
    }
              
    @Override
    protected void dispatchDraw(Canvas canvas){
        //行高
        int rHeight = getChildAt(0).getHeight();
        int width = getWidth();
        int rowNum = (int)Math.ceil(getChildCount()/(double)columnNum);
        //源绘制矩形
        Rect src = new Rect(0,0,rowBackground.getWidth(),rowBackground.getHeight());
        for(int i=0,y=rHeight-(rowBgHeight/2); i<rowNum; i++,y += rHeight){
            //目的绘制矩形
            Rect dst = new Rect(0,y,width,y+rowBgHeight);
            canvas.drawBitmap(rowBackground,src,dst,null);
        }
        super.dispatchDraw(canvas);
    }
}

上面第11行有这样一句

1
columnNum = attrs.getAttributeIntValue(NAMESPACE_ANDROID,"numColumns",3);

为什么不用getNumColumns?因为这个函数需要api level 11(即Android 3.0以上),而且有可能返回-1

两个自定义属性:背景和背景高度,在values/attrs.xml定义如下

1
2
3
4
5
6
7
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="row_bg_grid_view">
        <attr name="row_background" format="reference"/>
        <attr name="row_bg_height" format="dimension" />
    </declare-styleable>
</resources>

最后使用的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical">
    <com.best.oa.common.base.RowGridView
            android:id="@+id/functions"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dip"
            android:layout_weight="1"
            android:numColumns="2"
            oa:row_background="@drawable/grid_row_bg"
            oa:row_bg_height="60dip"
            android:stretchMode="columnWidth">
    </com.best.oa.common.base.RowGridView>
</LinearLayout>
原文地址:https://www.cnblogs.com/Free-Thinker/p/3685455.html