1

Button does not work in Canvas. What you need to change / add the caller to a message? The button is created but does not respond when you press. Is it possible that the canvas is over the button?

public class ButtonInCanvas extends AppCompatActivity implements View.OnClickListener {
Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        button = new Button(ButtonInCanvas.this);
        button.setOnClickListener(this);
        button.setText("OK!");
       setContentView(new BtInCanvas(ButtonInCanvas.this));
    }
    public class BtInCanvas extends View {

        public BtInCanvas(Context context) {

            super(context);
       }
        public void onDraw(Canvas canvas){
            button.layout(50,50,300,300);
            button.draw(canvas);
        }
    }

    @Override
    public void onClick(View v) {

        Toast.makeText(this,"OK!",Toast.LENGTH_LONG).show();
    }
}
nshmura
  • 5,940
  • 3
  • 27
  • 46
PeteGr
  • 23
  • 2
  • 4
  • you just draw a button image in your canvas with your code. You don't add it to a canvas. A canvas is not a ViewGroup to hold childViews. To handle clicks, you have to add onClickListener to your `BtInCanvas` view. But anyway your code looks like something very strange. Why do you need to add the button on the canvas? – Vladyslav Matviienko Aug 30 '16 at 07:27

1 Answers1

0

Let refer to the link Android drawing button to canvas with custom view?

"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
Jame
  • 3,746
  • 6
  • 52
  • 101