我是 Android 编程的初学者,我正在通过修改我找到的一些类来开发程序 here.到目前为止,我的 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
方法?
如有任何帮助,我们将不胜感激,谢谢。
P.S.:我尝试使用 XML 布局添加一个 Button,但现在我想用此类来制作它,并在 Main.java< 中设置 setContentView(new DrawView(this));
/p>
最佳答案
您不能在View的onDraw()
方法中添加其他View
对象,它们在View类中没有任何addView()
方法。
要使其正常工作,请使用 ViewGroup
扩展您的 DrawView 类。现在您可以在其中添加其他 View 。由于 addView()
方法属于 ViewGroup
类。
类似于,
public class DrawView extends ViewGroup {
关于java - 如何以编程方式将按钮添加到自定义 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12038288/