- 修改自定義視圖類, MyView.java, 重寫onTouchEvent(MotionEvent event)方法.
package com.AndroidView;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
public class MyView extends View {
private Paint myPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private Context myContext;
public MyView(Context context) {
super(context);
// TODO Auto-generated constructor stub
myContext = context;
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
myContext = context;
}
public MyView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
myContext = context;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// TODO Auto-generated method stub
//super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec),
MeasureSpec.getSize(heightMeasureSpec));
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
//super.onDraw(canvas);
int radius;
int height = getMeasuredHeight();
int width = getMeasuredWidth();
int centerX = width/2;
int centerY = height/2;
if (height>width){
radius = width/2;
}
else{
radius = height/2;
}
myPaint.setStyle(Paint.Style.STROKE);
myPaint.setColor(Color.WHITE);
myPaint.setStrokeWidth(1);
canvas.drawLine(centerX, centerY-10, centerX, centerY+10, myPaint);
canvas.drawLine(centerX-10, centerY, centerX+10, centerY, myPaint);
myPaint.setStrokeWidth(10);
myPaint.setColor(Color.RED);
canvas.drawRect(0, 0, width, height, myPaint);
myPaint.setStrokeWidth(3);
myPaint.setColor(Color.GREEN);
canvas.drawCircle(centerX, centerY, radius, myPaint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
int action = event.getAction();
if (action == MotionEvent.ACTION_DOWN){
Toast.makeText(myContext, "ACTION_DOWN", Toast.LENGTH_LONG).show();
}
else if (action == MotionEvent.ACTION_UP){
Toast.makeText(myContext, "ACTION_UP", Toast.LENGTH_LONG).show();
}
return true;
}
}
next: 要強制重繪View,調用invalidate()
沒有留言:
發佈留言