简体   繁体   中英

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. So far I have the DrawView class as follows:

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. How can I make this button appear, and add an onClick method too?

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)); in Main.java

You can not add other View objects in View's onDraw() method, their is no any addView() method in View class.

To get it work extend your DrawView class with ViewGroup now you can add other View in this. As addView() method belongs to ViewGroup Class.

Something like,

public class DrawView extends ViewGroup {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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