若既想使用GridView的網格排列,又想為每一列加上獨立背景,可以自訂一個MyGridView,在繪製階段手動貼上背景圖。
public class MyGridView extends GridView {
private Bitmap background;
public MyGridView(Context context, AttributeSet attrs) {
super(context, attrs);
background = BitmapFactory.decodeResource(getResources(), R.drawable.bg);
}
}
@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本身的捲動與排列特性。