我是 Android 开发的新手。我有一个扩展 View 的类 DrawView,它就像一个简单的绘图应用程序
public class DrawView extends View implements OnTouchListener {
Bitmap bitmap;
Canvas bitmapCanvas;
int color;
// Position of finger down
float pX, pY;
// Position of finger up
float mX, mY;
// Create new path
Path path = new Path();
// Is view initialized?!
boolean isInitialized;
// Create new paint
Paint paint = new Paint();
int begX, begY, endX, endY = 0;
//DrawView constructor
public DrawView(Context context) {
// Initialize new view
super(context);
setFocusable(false);
setFocusableInTouchMode(false);
this.setOnTouchListener(this);
requestLayout();
paint.setAntiAlias(true);
paint.setStyle(Style.STROKE);
// There is no bitmap yet
isInitialized = false;
}
//Initialize bitmap and canvas
private void init() {
bitmap = Bitmap.createBitmap(getWidth(), getHeight()/2, Bitmap.Config.RGB_565);
bitmap.setPixel(72, 72, Color.BLACK);
// Create new canvas and set bitmap
bitmapCanvas = new Canvas();
bitmapCanvas.setBitmap(bitmap);
// ... set canvas background color
bitmapCanvas.drawColor(Color.WHITE);
// We're done with initialization
isInitialized = true;
}
//Reset canvas
public void reset(){
bitmapCanvas.drawColor(Color.WHITE);
}
//Handle event 'onDraw'
@Override
public void onDraw(Canvas canvas) {
// Check if initialized
if (!isInitialized)
init();
// Draw bitmap!
canvas.drawBitmap(bitmap, 0, 0, paint);
}
//Handle event 'onTouch'
public boolean onTouch(View view, MotionEvent event) {
// Check event type
switch (event.getAction()) {
// Finger down
case MotionEvent.ACTION_DOWN:
paint.setColor(Color.BLACK);
paint.setStrokeWidth(7f);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeCap(Paint.Cap.ROUND);
paint.setAntiAlias(true);
// Get current position
pX = event.getX();
pY = event.getY();
// Set beginning of path to (posX,posY)
path.moveTo(pX, pY);
begX= (int) pX;
begY = (int) pY;
bitmapCanvas.drawPoint(pX, pY, paint);
break;
// Finger moves
case MotionEvent.ACTION_MOVE:
mX = event.getX();
mY = event.getY();
// Set position of end of path
path.lineTo(mX, mY);
endX = (int) mX;
endY = (int) mY;
// Draw path
bitmapCanvas.drawPath(path, paint);
// Invalidate canvas (redraw the view)
invalidate();
break;
// Finger up
case MotionEvent.ACTION_UP:
mX = event.getX();
mY = event.getY();
if (mY == pY && mX == pX){
bitmapCanvas.drawPoint(pX, pY, paint);
invalidate();
}
path.reset();
break;
}
return true;
}
}
在我的默认布局中,我希望它包含 DrawView 和其他元素(按钮、textview ...)
如何将“默认布局”拆分为包含带有这些元素的 DrawView?谢谢
编辑:我应该把这段代码放在哪里以使 DrawView 正常工作
public class Draw extends Activity {
DrawView drawView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
drawView = new DrawView(this);
setContentView(drawView);
drawView.requestFocus();
}
}