[英]Add Button to Custom View
I've tried extending LinearLayout
instead of simple View
for adding buttons and working children of View
but I am still not getting any output. 我尝试扩展LinearLayout
而不是简单的View
以添加按钮和View
工作子级,但是我仍然没有得到任何输出。 Conceptually I'm wrong somewhere. 从概念上讲,我在某处错了。
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;
}
}
The issue is that you are creating a new TouchEventView
and adding the Button
to that View
. 问题是您要创建一个新的TouchEventView
并将Button
添加到该View
。 Instead you should add the Button
directly to the current View
. 相反,您应该将Button
直接添加到当前View
。
You should also implement the other constructors from LinearLayout
if you want to be able to get any attributes from XML. 如果您希望能够从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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.