GridView将其元素绘制在一行中

时间:2013-09-25 22:36:59

标签: android gridview android-canvas android-custom-view

我正在尝试在画布上绘制GridView。我有一个自定义视图,我重写它的onDraw来实现这一点。

@Override
public void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    canvas.save();
    canvas.translate(mPosX, mPosY);
    canvas.scale(mScaleFactor, mScaleFactor);
    li = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    gridView = (GridView)li.inflate(R.layout.activity_main, null);
    gridView.setAdapter(mImageAdapter);
    gridView.setDrawingCacheEnabled(true);
    Bitmap cac = getDrawingCache();
    if(cac != null) {

        canvas.drawBitmap(cac, 0, 0, new Paint());
    } else {

        gridView.measure(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT);
        gridView.layout(0, 0, gridView.getMeasuredWidth(), gridView.getMeasuredHeight());
        gridView.draw(canvas);
    }
    canvas.restore();
}

这里是GridView的XML:

android:orientation="vertical"
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:columnWidth="90dp"
android:numColumns="auto_fit"
android:verticalSpacing="1dp"
android:horizontalSpacing="1dp"
android:stretchMode="columnWidth"
android:gravity="center">

GridView被绘制,但所有图像都绘制在一行中。 我想我可能要覆盖这个GridView上的onMeasure,但我不知道如何继续。请帮帮我!

1 个答案:

答案 0 :(得分:3)

您对measure()的来电是错误的。此方法将“测量规格”作为参数,可以使用View.MeasureSpec类构建。在你的情况下你想要的是:

int widthSpec = MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.AT_MOST);
int heightSpec = MeasureSpec.makeMeasureSpec(getHeight(), MeasureSpec.EXACTLY);
gridView.measure(widthSpec, heightSpec);

这是您的WRAP_CONTENT / MATCH_PARENT转换为度量规范。