[英]How to Add Button to Custom View Programmatically?
我是Android编程的入门者,并且正在通过修改在此找到的一些类来开发程序。 到目前为止,我具有DrawView
类,如下所示:
public class DrawView extends View {
private Ball ball1;
private Button kapabut;
public DrawView(Context context) {
super(context);
setFocusable(true);
ball1 = new Ball(context,R.drawable.ortatop);
kapabut=new Button(context); //here, I cannot seem to add a button.
kapabut.setVisibility(VISIBLE);
kapabut.setText("xXx");
}
@Override protected void onDraw(Canvas canvas) {
// move the balls at every canvas draw
ball1.moveBall();
//draw the balls on the canvas
canvas.drawBitmap(ball1.getBitmap(), ball1.x, ball1.y, null);
// refresh the canvas
invalidate();
}
}
球已创建并移动,但我似乎无法在任何位置获得“ kapabut”按钮。 如何显示此按钮,并添加onClick
方法?
任何帮助,将不胜感激,谢谢。
PS:我尝试过并使用XML布局添加了一个Button,但是现在我想使用此类进行设置,并设置setContentView(new DrawView(this));
在Main.java中
您不能在View的onDraw()
方法中添加其他View
对象,它们在View类中没有任何addView()
方法。
要使其工作正常,请使用ViewGroup
扩展DrawView类,现在可以在其中添加其他View。 由于addView()
方法属于ViewGroup
类。
就像是,
public class DrawView extends ViewGroup {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.