OnDraw()方法没有被调用

时间:2011-04-08 10:26:27

标签: android view ondraw

// DrawTargetMarker.java

    public class DrawTargetMarker extends View {
    //Class type variables
    private SurfaceHolder mHolder;
    private static final String TAG = DrawTargetMarker.class.getSimpleName();
    private int mX, mY;
    private int mRadius = 10;

    //Constructor
    public DrawTargetMarker(Context context, int curX, int curY){
        super(context);
        this.mX = curX;
        this.mY = curY;
        // Forces the canvas to draw the object
        invalidate();
    }
    @Override
    public void onDraw(Canvas canvas){
        super.onDraw(canvas);
        // Creating paint instance
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        // Setting the paint's style 
        paint.setStyle(Style.FILL);
        // Setting the width of the stroke
        paint.setStrokeWidth(5);
        // Setting the color of the object to be drawn
        paint.setColor(Color.BLACK);
        // Draw the circle using the specified paint
        canvas.drawCircle(mX, mY, mRadius, paint);  
    }
}

// RecordShots.java

...
...
....


recordShots.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            recordCount.setText(String.valueOf(count++));
            Log.i(TAG, "Points Recorded ( " + ((TargetTrackerGlobalVariable) getApplicationContext()).getCurrent_x() + "," + ((TargetTrackerGlobalVariable) getApplicationContext()).getCurrent_y() + ")");
            mDrawTargetMarker = new DrawTargetMarker(getApplicationContext(), ((TargetTrackerGlobalVariable) getApplicationContext()).getCurrent_x(), ((TargetTrackerGlobalVariable) getApplicationContext()).getCurrent_y());

// points recorded will be showing two values like (120,20), depending upon the object 
// position in the view.            


        }

    });

所以,我的查询是当我点击按钮时,以(x,y)的形式向我显示对象在视图中的确切位置,但我试图将x,y与上下文一起传递给视图,所以在那个x,我需要放置一个对象并重复该过程直到我结束。

所以Control正在移动到视图,但问题是OnDraw()方法无法被调用,它负责在指定的x,y中绘制对象。

1 个答案:

答案 0 :(得分:1)

理想情况下,您需要将DrawTargetMarker附加到活动的主视图中(请参阅setContentView)。当您使用intent启动Activity时,应直接调用View的onDraw()方法。你不应该直接调用DrawTargetMarker构造函数。