Problem
You basically want a Android GridView, but you want to have a background for each row. Or, you want a ListView with multiple columns. Or, you want a TableLayout with a dynamic number of columns. In fact, anything that has a dynamic number of columns (like a GridView) with a custom bakground for each row (like a ListView).
I had this problem, and this is how I solved it. Note that, as with many problems, this is only one of many possible solutions.
Solution
Create a new class, let’s call it ‘MyGridView’, and let it extend GridView. Create a new constructor with Context and AttributeSet parameters so you can use this class in your layout XML files. This is also a good point to load your background image.
public class MyGridView extends GridView { private Bitmap background; public MyGridView(Context context, AttributeSet attrs) { super(context, attrs); background = BitmapFactory.decodeResource(getResources(), R.drawable.bg); } }
Then, override GridView#dispatchDraw(Canvas canvas). This method is called on every draw, before the items will be drawn. An ideal point to paint your custom background! Now, since you load your background in the constructor, you can use it in dispatchDraw() like this:
@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); }
Done! You can use this custom GridView in your layout XML files like this:
<your.package.name.MyGridView android:id="@+id/mygridview" <!-- other GridView configuration parameters --> />
posted on 2012-05-10 15:46
汪杰 阅读(408)
评论(0) 编辑 收藏 引用