Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Android GridView自訂每行背景

若既想使用GridView的網格排列,又想為每一列加上獨立背景,可以自訂一個MyGridView,在繪製階段手動貼上背景圖。

自訂GridView

public class MyGridView extends GridView {
    private Bitmap background;

    public MyGridView(Context context, AttributeSet attrs) {
        super(context, attrs);
        background = BitmapFactory.decodeResource(getResources(), R.drawable.bg);
    }
}

重寫dispatchDraw

@Override
protected void dispatchDraw(Canvas canvas) {
    int count = getChildCount();
    int top = count > 0 ? getChildAt(0).getTop() : 0;
    int backgroundWidth = background.getWidth();
    int backgroundHeight = background.getHeight();
    int width = getWidth();
    int height = getHeight();

    for (int y = top; y < height; y += backgroundHeight) {
        for (int x = 0; x < width; x += backgroundWidth) {
            canvas.drawBitmap(background, x, y, null);
        }
    }

    super.dispatchDraw(canvas);
}

版面使用

<your.package.name.MyGridView
    android:id="@+id/mygridview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" />

這種做法不需要動態計算欄數,也能保留GridView本身的捲動與排列特性。

Copyright © Linux教程網 All Rights Reserved