asfman
android developer
posts - 90,  comments - 213,  trackbacks - 0

Android – Row background in GridView
from http://erikw.eu/android-row-background-in-gridview/

Posted on 08/11/2010 by Erik Wallentinsen

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)  编辑 收藏 引用
只有注册用户登录后才能发表评论。

<2024年12月>
24252627282930
1234567
891011121314
15161718192021
22232425262728
2930311234

常用链接

留言簿(15)

随笔分类(1)

随笔档案(90)

文章分类(727)

文章档案(712)

相册

收藏夹

http://blog.csdn.net/prodigynonsense

友情链接

最新随笔

搜索

  •  

积分与排名

  • 积分 - 468991
  • 排名 - 6

最新随笔

最新评论

阅读排行榜

评论排行榜