Android开发教程:GridView为每行设定背景


如果你既想使用GridView,又想给每行设置单独的背景,该怎么办呢?也许你说,用Listview或TableLayout就好了,但是使用这两个控件比较麻烦的是需要动态计算出列数。

所以想要解决这个问题,需要用如下方法:

首先定义一个类‘MyGridView’继承自GridView,设置每行用到的背景。

  1. public class MyGridView extends GridView {   
  2.     
  3.     private Bitmap background;   
  4.     
  5.     public MyGridView(Context context, AttributeSet attrs) {   
  6.         super(context, attrs);   
  7.         background = BitmapFactory.decodeResource(getResources(), R.drawable.bg);   
  8.     }   
  9.     
  10. }  

其次复写GridView的dispatchDraw(Canvas canvas)方法自定义背景

  1. @Override  
  2. protected void dispatchDraw(Canvas canvas) {   
  3.     int count = getChildCount();   
  4.     int top = count>0 ? getChildAt(0).getTop() : 0;   
  5.     int backgroundWidth = background.getWidth();   
  6.     int backgroundHeight = background.getHeight();   
  7.     int width = getWidth();   
  8.     int height = getHeight();   
  9.     
  10.     for (int y = top; y<height; y += backgroundHeight){   
  11.         for (int x = 0; x<width; x += backgroundWidth){   
  12.             canvas.drawBitmap(background, x, y, null);   
  13.         }   
  14.     }   
  15.     
  16.     super.dispatchDraw(canvas);   
  17. }  

好了,现在可以用在Xml里了,看看效果吧

  1. <your.package.name.MyGridView  
  2.     Android:id="@+id/mygridview"  
  3.     <!-- GridView 其他属性 -->  
  4.     />  

相关内容