我尝试过LinearLayout
而不是简单View
来添加View
的按钮和工作孩子,但我仍然没有得到任何输出。从概念上讲,我在某处错了。
public class TouchEventView extends LinearLayout {
private Paint paint = new Paint();
private Path path = new Path();
private ViewGroup viewGroup;
public TouchEventView(Context ctx) {
super(ctx);
//Button Code Starts Here
LinearLayout touch = new TouchEventView(ctx);
Button bt = new Button(ctx);
bt.setText("A Button");
bt.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
touch.addView(bt); //Button Not Working
paint.setAntiAlias(true);
paint.setColor(Color.BLACK);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(5f);
this.setBackgroundColor(Color.WHITE);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawPath(path,paint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPos = event.getX();
float yPos = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
path.moveTo(xPos,yPos);
return true;
case MotionEvent.ACTION_MOVE:
path.lineTo(xPos,yPos);
break;
case MotionEvent.ACTION_UP:
break;
default:
return false;
}
invalidate();
return true;
}
}
答案 0 :(得分:2)
问题是您要创建新的TouchEventView
并将Button
添加到View
。相反,您应该将Button
直接添加到当前View
。
如果您希望能够从XML获取任何属性,还应该从LinearLayout
实现其他构造函数。
public class TouchEventView extends LinearLayout {
public TouchEventView(Context context) {
this(context, null);
}
public TouchEventView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public TouchEventView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
Button button = new Button(getContext());
button.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
addView(button);
}
}