我有这堂课:
public class MainActivity extends Activity{
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);//LOAD MY LAYOUT
}
}
还有更多代码(显然)。我有下一个用户界面:
我想画一条线来模拟图像之间的联合。
我试过:
Canvas canvas = new Canvas();
Paint paint = new Paint();
paint.setColor(Color.BLACK);
canvas.drawLine(0, 0, 300, 700, paint);
(上面只是测试我是否可以画一条线。)但是我不能画任何东西,因为当我在我的活动中创建这样的画布时,它没有附加到任何东西上,我只是在一个表面上画永远不是屏幕的一部分。
因此,我有以下课程。
public class MainActivity extends Activity {
/** Called when the activity is first created. */
Paint mPaint;
float Mx1,My1;
float x,y;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyView view1 =new MyView(this);
setContentView(view1);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setColor(0xFFFF0000);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeWidth(10);
}
public class MyView extends View {
private Bitmap mBitmap;
private Canvas mCanvas;
private Path mPath;
private Paint mBitmapPaint;
public MyView(Context c) {
super(c);
mPath = new Path();
mBitmapPaint = new Paint(Paint.DITHER_FLAG);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(0xFFAAAAAA);
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
canvas.drawPath(mPath, mPaint);
}
private float mX, mY;
private static final float TOUCH_TOLERANCE = 4;
private void touch_start(float x, float y) {
mPath.reset();
mPath.moveTo(x, y);
mX = x;
mY = y;
}
private void touch_move(float x, float y) {
float dx = Math.abs(x - mX);
float dy = Math.abs(y - mY);
if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
mX = x;
mY = y;
}
}
private void touch_up() {
mPath.lineTo(mX, mY);
// commit the path to our offscreen
mCanvas.drawPath(mPath, mPaint);
// kill this so we don't double draw
mPath.reset();
}
@Override
public boolean onTouchEvent(MotionEvent event){
float x = event.getX();
float y = event.getY();
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
touch_start(x, y);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
touch_move(x, y);
invalidate();
break;
case MotionEvent.ACTION_UP:
touch_up();
invalidate();
break;
}
return true;
}
}
}
这是我找到的一个例子。在视图类中,方法:
setContentView(R.layout.main);
不起作用。
我的问题是:如何在扩展的 View 类中加载我的 UI(我已设置为图像)?因为在示例中我只是加载一个空屏幕。我不知道如何加载我的布局 file.xml
谢谢你的帮助!!!