12

How can I draw a button on top of the canvas in a custom view? (Preferably on the mid-right side) Is there something I have to call before doing the button.draw(canvas)?

    public class MyClass extends View {
    public Simulation(Context context) {
            super(context);
            pauseButton.setText("TestButton");
            pauseButton.setClickable(true);
            pauseButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            Log.i(TAG, "Button Pressed!");
            }
            });
    public onDraw(Canvas canvas) {
           super.onDraw(canvas);
           pauseButton.draw(canvas);
    }
    }

Thanks for your time

unknownone
  • 368
  • 2
  • 5
  • 13

3 Answers3

16

You cannot insert a button into canvas. Canvas is an interface for bitmap or a bitmap buffer for a view. You can only draw other bitmap or pixels in it, not insert an object or a widget.

There are some solutions:

  1. as Nikolay suggested, use a FrameLayout and create two layers (views), first your custom view and the second LinerView or RelativeView, which will come on top, where you can have buttons etc

  2. draw an image of a buttun on Canvas then use onTouchEvent in your custom view and test for the coordinates of the touch, then do something... an example for onTouchEvent here: Make certain area of bitmap transparent on touch

Community
  • 1
  • 1
Lumis
  • 21,517
  • 8
  • 63
  • 67
  • How would I add my custom view to the xml file? Thanks for your answer – unknownone Aug 14 '11 at 01:58
  • 1
    That is a long story, you have to search for examples...but basically you create a new tag like .... in xml and then create a new class called MyView extends View which has a constructor MyView(Context context, AttributeSet attrs){ super(context, attrs); ....} in this example just add the constructor i mentioned: http://stackoverflow.com/questions/6308106/view-inflation-and-custom-views – Lumis Aug 14 '11 at 08:04
6

Why do you need to draw the button yourself? Use a FrameLayout and simply have the button overlayed on your custom view.

Nikolay Elenkov
  • 52,576
  • 10
  • 84
  • 84
-1

Try this

public onDraw(Canvas canvas) {
       super.onDraw(canvas);
       canvas.save();
       pauseButton.draw(canvas);
       canvas.restore();
}
Ron
  • 24,175
  • 8
  • 56
  • 97