android 自定义Button,抛弃写shape文件

来源:互联网 发布:安卓去广告软件 编辑:程序博客网 时间:2024/05/18 00:14

前言

  • 在日常的android开发当中,按钮是必不可少控件。但是如果要实现下面的效果恐怕写shape文件都要写的头晕

w(゚Д゚)ww(゚Д゚)w,所以为了以后的开发,我们就简单的封装下。

这里写图片描述

代码块

很简单我们通过GradientDrawable 类就可以实现啦。

public class ButtonStyle extends Button {     GradientDrawable gradientDrawable;    //按下颜色    private int pressedColor=Color.GRAY;    //当前颜色    private int normalColor=Color.RED;    //当前圆角    private float currCorner=5;    //四边边框宽度    private float strokeWidth=0;    //四边边框颜色    private int strokeColor;     boolean isTouchPass = true;    public ButtonStyle(Context context) {        this(context, null);    }    public ButtonStyle(Context context, AttributeSet attrs) {        this(context, attrs, 0);    }    public ButtonStyle(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);        init();    }     private void init() {        setGravity(Gravity.CENTER);        gradientDrawable = new GradientDrawable();        //设置按钮颜色        gradientDrawable.setColor(normalColor);        //设置按钮的边框宽度        gradientDrawable.setStroke((int) strokeWidth, strokeColor);        //设置按钮圆角大小        gradientDrawable.setCornerRadius(currCorner);        //设置按钮点击之后的颜色更换        setOnTouchListener(new OnTouchListener() {            @Override            public boolean onTouch(View arg0, MotionEvent event) {                setBackgroundDrawable(gradientDrawable);                return setColor(event.getAction());            }        });        setBackgroundDrawable(gradientDrawable);    }    //处理按钮点击事件无效    @Override    public void setOnClickListener(OnClickListener l) {        super.setOnClickListener(l);        isTouchPass = false;    }   //处理按下去的颜色   public boolean setColor(int action) {        switch (action) {            case MotionEvent.ACTION_DOWN:                gradientDrawable.setColor(pressedColor);                break;            case MotionEvent.ACTION_UP:                gradientDrawable.setColor(normalColor);                break;            case MotionEvent.ACTION_CANCEL:                gradientDrawable.setColor(normalColor);                break;        }        return isTouchPass;    }}

这样就完成了!很简单是吧 (〃` 3′〃) (〃` 3′〃)

具体的可以看我自己封装的能给个start那是最好啦 23333

Dome –> https://github.com/laishujie/ButtonStyle

原创粉丝点击