android使用gridview的书架效果

android使用gridview的书架效果,需要使用自定义的gridview来填充每行的背景,核心代码如下:

BookGridView.java

/**
 * 书架效果
 *
 */
public class BookGridView extends GridView {

	private Bitmap background;
	Context context;

	public BookGridView(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.context = context;
		background = null;
	}

	@Override
	protected void dispatchDraw(Canvas canvas) {
		int count = getChildCount();
		int top = count > 0 ? getChildAt(0).getTop() : 0;

		int width = getWidth();
		int height = getHeight();

		int totalCount = this.getCount();

		//如果总数为0自然没必要计算高度并画图
		if (totalCount > 0) {
			
			//获取列数
			int numColumns=3;
			// 计算行高,通过行数和控件高度计算
			int rowCount = totalCount / numColumns;
			if (totalCount % numColumns != 0) {
				rowCount++;
			}
			int rowHeight = height / rowCount;


			if (background == null) {
				background = BitmapFactory.decodeResource(getResources(),
						R.drawable.bookshelf_layer_center);
				background = Bitmap.createScaledBitmap(background, width,
						rowHeight, true);
			}

			int backgroundWidth = background.getWidth();
			int backgroundHeight = background.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);
	}

}

 

 

使用如下:

            

  具体可以参照:

http://blog.csdn.net/caizhegnhao/article/details/38857531 ,附件给出它的下载源码

你可能感兴趣的:(android)