Question

I am implementing a custom view. I want to add a bunch of circles to a FrameLayout when a user touches a point in the ImageView hosted inside of the FrameLayout. Right now, I am drawing inside the onDraw method with a radius of 20. But, when I put it into the FrameLayout, it just shows a tiny corner. How can I tell the custom view that it should have a width/height of 20 as well? Is this something I should do within my custom view, or in the activity where I call addView once I instantiate the custom view?

public class MyCircle extends View {

Paint paint;
private static final int RADIUS = 20;

public MyCircle(Context context) {
    super(context);
    paint = new Paint();
    paint.setColor(Color.WHITE);
    setLayoutParams(new ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT));
//        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams( RADIUS * 2 , RADIUS * 2 );
//        setLayoutParams(layoutParams);
}

@Override
public void onDraw( Canvas canvas ) {
    canvas.drawCircle(0, 0, RADIUS, paint );
}
}

The activity code is basically this (called from within a onTouch handler with X/Y coordinates):

    MyCircle circle;
    circle = new MyCircle(this);
    circle.setX( x );
    circle.setY( y );
    FrameLayout root = (FrameLayout)findViewById(R.id.image_review_frame);
    root.addView( circle );
Was it helpful?

Solution

Override onMeasure()

@Override
protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec)
{
 float density = context.getResources().getDisplayMetrics().density;
 setMeasuredDimension (RADIUS * density,RADIUS * density);
 return;
}

the code re:density is to convert dp to pixels (e.g. xhdpi displays will have density 2.0)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top