Search code examples
androidgridviewandroid-canvasandroid-custom-view

GridView drawing its elements in a single row


I’m trying to draw a GridView on a canvas. I have a custom view and I'm overriding its onDraw to achieve this.

@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();
}

Hereis the XML of the GridView :

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">

The GridView gets drawn, but all the images are drawn in a single row. I think I might have to Override the onMeasure on this GridView, but I'm not sure how to proceed. Please help me out !


Solution

  • Your call to measure() is wrong. This method takes "measure specs" as parameters, which can be built using the View.MeasureSpec class. In your case what you want is:

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

    This is the translation of your WRAP_CONTENT/MATCH_PARENT into measure specs.