1

我正在尝试在画布上绘制 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,但我不确定如何继续。请帮帮我!

4

1 回答 1

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转换为测量规格。

于 2013-09-25T22:54:45.337 回答