简体   繁体   English

如何以编程方式向自定义视图添加按钮?

[英]How to Add Button to Custom View Programmatically?

I'm a starter in Android Programming, and I'm developing a program by modifying some classes I found here. 我是Android编程的入门者,并且正在通过修改在找到的一些类来开发程序 So far I have the DrawView class as follows: 到目前为止,我具有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();
    }    
}

The ball is created and moves, but I cannot seem to get the button "kapabut" anywhere. 球已创建并移动,但我似乎无法在任何位置获得“ kapabut”按钮。 How can I make this button appear, and add an onClick method too? 如何显示此按钮,并添加onClick方法?

Any help would be appreciated, thanks. 任何帮助,将不胜感激,谢谢。

PS: I tried and added a Button using an XML layout, but now I want to make it with this class, and setting setContentView(new DrawView(this)); PS:我尝试过并使用XML布局添加了一个Button,但是现在我想使用此类进行设置,并设置setContentView(new DrawView(this)); in Main.java 在Main.java中

You can not add other View objects in View's onDraw() method, their is no any addView() method in View class. 您不能在View的onDraw()方法中添加其他View对象,它们在View类中没有任何addView()方法。

To get it work extend your DrawView class with ViewGroup now you can add other View in this. 要使其工作正常,请使用ViewGroup扩展DrawView类,现在可以在其中添加其他View。 As addView() method belongs to ViewGroup Class. 由于addView()方法属于ViewGroup类。

Something like, 就像是,

public class DrawView extends ViewGroup {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM