使用的onDraw Android扩展按钮 [英] extending android button by using onDraw

查看:161
本文介绍了使用的onDraw Android扩展按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想改变我的按钮形状的但我想用onDaw方法和扩展按钮
类。所以,我刚才做了最开始是:

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"
     />

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

推荐答案

设置背景为透明的XML(就像<一个href=\"http://stackoverflow.com/questions/24573667/extending-android-button-ondraw#comment38065114_24573667\">hypd09说的),并覆盖onTouchListener因此点击次数,如果你点击你的蓝色圆圈才能正常工作。

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来控制,如果点击位置是在蓝色圆圈。你可以触摸位置如这个

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

您甚至可以允许在下列方式设置onClickListener(添加到您用作MyButton类):

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

这篇关于使用的onDraw Android扩展按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆