Chain Cross
Chain Cross

Reputation: 351

Can't add custom view dynamically with WRAP_CONTENT as height and width

I am trying to add multiple custom views to a frame layout but it always takes the whole width and height of the frame layout. The custom view only contains a 50x50 image which I want to be able to move around the frame layout, but as the custom view takes the whole space and overlaps with each other, I cannot select other custom views, hence why I want it wrapped.

Here's how I'm adding the custom views :

OverlayView overlayView = new OverlayView(EditorActivity.this, themeFilter.drawable);
frameLayout.addView(overlayView, 1, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT));

Here is the OverlayView :

public class OverlayView extends View {

    Bitmap bitmap;
    float x,y;
    float centerX, centerY;

    public OverlayView(Context context, int drawable) {
        super(context);
    bitmap = BitmapFactory.decodeResource(context.getResources(), drawable);
    centerX = (float)getWidth() /2;
    centerY = (float)getHeight() /2;
    x = centerX;
    y = centerY;
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    if (x != centerX && y != centerY) {
        canvas.drawBitmap(bitmap, x-bitmap.getWidth()/2, y-bitmap.getHeight()/2, null);
    } else {
        //INITIALIZE BITMAP ON CENTER OF SCREEN
        canvas.drawBitmap(bitmap, (float)getWidth()/2 - bitmap.getWidth()/2, (float)getHeight()/2 -bitmap.getHeight()/2, null);
    }
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    switch(event.getAction()) {
        case MotionEvent.ACTION_DOWN :
            break;
        case MotionEvent.ACTION_MOVE :
            x = event.getX();
            y = event.getY();
            invalidate();
            break;
        case MotionEvent.ACTION_UP :
            x = event.getX();
            y = event.getY();
            invalidate();
    }
    return true;
}

}

Right now what I'm thinking is keep it as is. Meaning, the OverlayView takes on the whole screen and I just have to switch focus between other OverlayViews to be able to move them (I don't even know if this is possible- switching focus between stacked OverlayViews) but I'm worried about the wasted space affecting memory and performance as the image is only 50x50.

Upvotes: 1

Views: 1315

Answers (1)

Crispert
Crispert

Reputation: 1167

The size of the OverlayView is computed in onMeasure(). Try this implementation:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) 
{
    int width = View.MeasureSpec.makeMeasureSpec(bitmap.getWidth(), MeasureSpec.EXACTLY);
    int height = View.MeasureSpec.makeMeasureSpec(bitmap.getHeight(), MeasureSpec.EXACTLY);
    setMeasuredDimension(width, height);
}

Also have a look at this implementation for onMeasure.

Upvotes: 2

Related Questions