Search code examples
androidandroid-viewandroid-custom-viewandroid-button

extending android button by using onDraw


I want to change my button shape BUT I WANT TO USE onDaw method and EXTENDING button class. So what I've just done for the beginning is :

     <view class = "com.example.button.MainActivity$MyButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
     />

and

    public static class MyButton extends Button {


     public MyButton(Context context) {
      super(context);

     }

     public MyButton(Context context, AttributeSet attrs) {
      super(context, attrs);

     }

     public MyButton(Context context, AttributeSet attrs, int defStyle) {
      super(context, attrs, defStyle);

     }

     @Override
     protected void onDraw(Canvas canvas) {

            Paint paint = new Paint();
            paint.setColor(Color.BLUE);
            paint.setStrokeWidth(10);
            paint.setStyle(Style.FILL);
            int width = getWidth();
            int height = getHeight();
            canvas.drawCircle(width/2, height/2, height/3, paint);

      } 
}

but I get a blue circle on a button view rectangular.

I want to see just the blue circle as a button shape and I get ride of the rectangular. Any help ??


Solution

  • Set background to transparent in xml (just like hypd09 said) and override onTouchListener so the clicks only work if you click your blue circle.

    setOnTouchListener to control if the click position was within blue circle. You can get the touch position like this.

    You can even allow for setting the onClickListener in a following way (add this to your MyButton class):

    @Override
    public void setOnClickListener(final OnClickListener onClickListener) {
        MyButton.this.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event){
                if (isWithinCircle(event))
                {
                    onClickListener.onClick(v);
                }
            }
        });
    }