0

我有这门课

MyTouchEventView.java

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;

public class MyTouchEventView extends View {

private Paint paint = new Paint();
private Path path = new Path();
private Path circlePath = new Path();

public Button btnReset;
public LayoutParams params;

public MyTouchEventView(Context context) {
    super(context);

    paint.setAntiAlias(true);
    paint.setColor(Color.GREEN);
    paint.setStyle(Paint.Style.STROKE);
    paint.setStrokeJoin(Paint.Join.ROUND);
    paint.setStrokeWidth(4f);

    btnReset = new Button(context);
    btnReset.setText("Clear Screen");

    params = new LayoutParams(LayoutParams.MATCH_PARENT,
            LayoutParams.WRAP_CONTENT);
    btnReset.setLayoutParams(params);

    btnReset.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            path.reset();
            postInvalidate();

        }
    });

}

@Override
protected void onDraw(Canvas canvas) {

    canvas.drawPath(path, paint);
}

@Override
public boolean onTouchEvent(MotionEvent event) {

    float pointX = event.getX();
    float pointY = event.getY();

    switch (event.getAction()) {
    case MotionEvent.ACTION_DOWN:
        path.moveTo(pointX, pointY);

        return true;
    case MotionEvent.ACTION_MOVE:
        path.lineTo(pointX, pointY);
        circlePath.reset();

        circlePath.addCircle(pointX, pointY, 30, Path.Direction.CW);

        break;

    case MotionEvent.ACTION_UP:
        circlePath.reset();

        break;
    default:
        return false;
    }

    postInvalidate();
    return true;
}
}

画笔.java

public class DrawingBrush extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    MyTouchEventView tv = new MyTouchEventView(this);
    setContentView(tv);
    addContentView(tv.btnReset, tv.params);
}

@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    finish();
}

}

现在我想转换这个

    MyTouchEventView tv = new MyTouchEventView(this);
setContentView(tv);
addContentView(tv.btnReset, tv.params);

作为 setContentView(R.layout.main); 并将按钮和其他组件放在“main.xml”布局中

我怎样才能做到这一点?希望有人明白我的意思。

4

1 回答 1

2

MyTouchEventView应该至少还有一个构造函数。这个构造函数应该接受一个AttributeSet参数,除了Context.

public MyTouchEventView (Context context, AttributeSet attrs) {
  // perform initialization
}

当在 XML 布局文件中声明视图时,它将被调用。

然后,您可以像这样在 XML 中声明视图:

<com.my_package_name.MyTouchEventView
     ....
      />

此主题在 Android 文档中有详细说明。看看这里:http: //developer.android.com/training/custom-views/index.html

于 2013-07-15T14:01:43.567 回答