extending android button by using onDraw

孤者浪人 提交于 2019-12-23 13:19:59

问题


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 ??


回答1:


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);
            }
        }
    });
}


来源:https://stackoverflow.com/questions/24573667/extending-android-button-by-using-ondraw

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!