自定義波紋點擊效果的Button

背景

不知道大家在開發md風格的項目中,各種形狀各種顏色的Button是怎么實現的,對于我這樣的一個菜鳥來說,就傻傻的一種樣式寫一個<ripple/>,這樣一個項目下來包含大量定義按鈕樣式的xml文件,不但看著蛋疼,后期維護起來也非常惱火,于是乎開始自定義按鈕吧。

自定義按鈕

說起自定義View其實并不難,這里的自定義Button更加簡單,都不用重寫onDraw、onLayout、onMeasure等方法,那就直接上代碼,是在不明白的同學請學習下自定義控件的基礎知識。
首先是直接在項目的res/values下新建一個attrs.xml文件,然后在里面定義一些可能用到的屬性

<!--自定義Button屬性-->
    <declare-styleable name="CustomButton">
        <attr name="bgColor" format="color" />
        <attr name="bgColorPress" format="color" />
        <attr name="bgColorDisable" format="color" />
        <attr name="textColor" format="color" />
        <attr name="textColorPress" format="color" />
        <attr name="textColorDisable" format="color" />
        <attr name="cornersRadius" format="float" />
        <attr name="shape">
            <enum name="rectangle" value="0" />
            <enum name="oval" value="1" />
            <enum name="line" value="2" />
            <enum name="ring" value="3" />
        </attr>
        <attr name="strokeWidth" format="integer" />
        <attr name="strokeColor" format="color" />
        <attr name="rippleColor" format="color" />
    </declare-styleable>

這里根據需求定義了以上屬性,當如如果有更復雜的需求就定義相應的屬性,各位大神自由發揮。
然后就是新建一個類CustomButton繼承自Button,把所有屬性列舉出來,然后獲取相應屬性的值即可,由于比較簡單,注釋也比較詳細,就直接貼代碼了
CustomButton.java

package com.liuqiang.customviewlibrary;

import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.RippleDrawable;
import android.graphics.drawable.StateListDrawable;
import android.util.AttributeSet;
import android.widget.Button;

/**
 * Created by liuqiang on 2017/11/3.
 * 自定義帶波紋點擊效果的Button,支持圓角矩形,圓形按鈕等樣式,可通過配置文件改變按下后的樣式
 */
public class CustomButton extends Button {
    private static String TAG = "CustomButton";
    private Context mContext;
    /**
     * 按鈕的背景色
     */
    private int bgColor = 0;
    /**
     * 按鈕被按下時的背景色
     */
    private int bgColorPress = 0;
    /**
     * 按鈕不可用的背景色
     */
    private int bgColorDisable = 0;

    /**
     * 按鈕正常時文字的顏色
     */
    private int textColor;
    /**
     * 按鈕被按下時文字的顏色
     */
    private int textColorPress;
    /**
     * 按鈕不可點擊時文字的顏色
     */
    private int textColorDisable;
    /**
     * 按鈕的形狀
     */
    private int shapeType;
    /**
     * 矩形時有效,4個角的radius
     */
    private float cornersRadius;
    /**
     * 邊框線寬度
     */
    private int strokeWidth = 0;
    /**
     * 邊框線顏色
     */
    private int strokeColor;

    private ColorStateList rippleColor;


    //shape的樣式
    public static final int RECTANGLE = 0;
    public static final int OVAL = 1;
    public static final int LINE = 2;
    public static final int RING = 3;



    private GradientDrawable gradientDrawable = null;



    public CustomButton(Context context) {
        this(context,null);
    }

    public CustomButton(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public CustomButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        getAttr(attrs);
        init();
    }

    private void getAttr(AttributeSet attrs) {
        if (attrs == null) {
            return;
        }
        TypedArray a = mContext.obtainStyledAttributes(attrs, R.styleable.CustomButton);
        if (a != null) {
            bgColor = a.getColor(R.styleable.CustomButton_bgColor, 0);
            bgColorPress = a.getColor(R.styleable.CustomButton_bgColorPress, 0);
            bgColorDisable = a.getColor(R.styleable.CustomButton_bgColorDisable, 0);

            textColor = a.getColor(R.styleable.CustomButton_textColor, 0);
            textColorPress = a.getColor(R.styleable.CustomButton_textColorPress, 0);
            textColorDisable = a.getColor(R.styleable.CustomButton_textColorDisable, 0);

            shapeType = a.getInt(R.styleable.CustomButton_shape, GradientDrawable.RECTANGLE);
            cornersRadius = a.getFloat(R.styleable.CustomButton_cornersRadius, 0);

            strokeWidth = a.getInteger(R.styleable.CustomButton_strokeWidth,0);
            strokeColor = a.getColor(R.styleable.CustomButton_strokeColor,0);

            rippleColor = a.getColorStateList(R.styleable.CustomButton_rippleColor);
            if (rippleColor == null || rippleColor.getDefaultColor() == 0) {
                rippleColor = createRippleColorStateList(Color.GRAY);
            }
        }
    }
    private void init() {
        setClickable(true);
//        setBackground(getDrawable(android.R.attr.state_enabled));
        setBackground(getSelector());
        setTextColor(createColorStateList());
    }

    /**
     * 設置GradientDrawable
     *
     * @param state 按鈕狀態
     * @return gradientDrawable
     */
    public GradientDrawable getDrawable(int state) {
        gradientDrawable = new GradientDrawable();
        setShape();
        setBorder();
        setRadius();
        setSelectorColor(state);
        return gradientDrawable;
    }

    /**
     * 設置shape類型
     */
    private void setShape() {

        switch (shapeType) {
            case RECTANGLE:
                gradientDrawable.setShape(GradientDrawable.RECTANGLE);
                break;
            case OVAL:
                gradientDrawable.setShape(GradientDrawable.OVAL);
                break;
            case LINE:
                gradientDrawable.setShape(GradientDrawable.LINE);
                break;
            case RING:
                gradientDrawable.setShape(GradientDrawable.RING);
                break;
        }
    }
    /**
     * 設置邊框  寬度  顏色  虛線  間隙
     */
    private void setBorder() {
        gradientDrawable.setStroke(strokeWidth, strokeColor, 0, 0);
    }

    /**
     * 只有類型是矩形的時候設置圓角半徑才有效
     */
    private void setRadius() {
        if (shapeType == GradientDrawable.RECTANGLE) {
            if (cornersRadius != 0) {
                gradientDrawable.setCornerRadius(cornersRadius);//設置圓角的半徑
            }
        }
    }

    /**
     * 設置Selector的不同狀態的顏色
     *
     * @param state 按鈕狀態
     */
    private void setSelectorColor(int state) {
        switch (state) {
            case android.R.attr.state_pressed:
                gradientDrawable.setColor(bgColorPress);
                break;
            case -android.R.attr.state_enabled:
                gradientDrawable.setColor(bgColorDisable);
                break;
            case android.R.attr.state_enabled:
                gradientDrawable.setColor(bgColor);
                break;
        }
    }

    /**
     * 設置按鈕的Selector
     *
     * @return stateListDrawable
     */
    public Drawable getSelector() {
        StateListDrawable stateListDrawable = new StateListDrawable();
        //注意該處的順序,只要有一個狀態與之相配,背景就會被換掉
        //所以不要把大范圍放在前面了,如果sd.addState(new[]{},normal)放在第一個的話,就沒有什么效果了
        stateListDrawable.addState(new int[]{android.R.attr.state_pressed, android.R.attr.state_enabled}, getDrawable(android.R.attr.state_pressed));
        stateListDrawable.addState(new int[]{-android.R.attr.state_enabled}, getDrawable(-android.R.attr.state_enabled));
        stateListDrawable.addState(new int[]{}, getDrawable(android.R.attr.state_enabled));

        if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.LOLLIPOP) {
            return stateListDrawable;
        }else{

            RippleDrawable rippleDrawable = new RippleDrawable(rippleColor,stateListDrawable,null);
            return rippleDrawable;
        }
    }
    /** 設置不同狀態時其文字顏色 */
    private ColorStateList createColorStateList() {
        int[] colors = new int[] { textColorPress, textColorDisable, textColor};
        int[][] states = new int[3][];
        states[0] = new int[] { android.R.attr.state_pressed, android.R.attr.state_enabled };
        states[1] = new int[] { -android.R.attr.state_enabled};
        states[2] = new int[] { android.R.attr.state_enabled };
        ColorStateList colorList = new ColorStateList(states, colors);
        return colorList;
    }

    /** 設置默認ripple顏色 */
    private ColorStateList createRippleColorStateList(int color) {
        int[] colors = new int[] {color};
        int[][] states = new int[1][];
        states[0] = new int[] { };
        ColorStateList colorList = new ColorStateList(states, colors);
        return colorList;
    }

    /////////////////對外暴露的方法//////////////

    /**
     * 設置Shape類型
     *
     * @param type 類型
     * @return 對象
     */
    public CustomButton setShapeType(int type) {
        this.shapeType = type;
        return this;
    }


    /**
     * 設置按下的顏色
     *
     * @param color 顏色
     * @return 對象
     */
    public CustomButton setBgPressedColor(int color) {
        this.bgColorPress = getResources().getColor(color);
        return this;
    }

    /**
     * 設置正常的顏色
     *
     * @param color 顏色
     * @return 對象
     */
    public CustomButton setBgNormalColor(int color) {
        this.bgColor = getResources().getColor(color);
        return this;
    }

    /**
     * 設置不可點擊的顏色
     *
     * @param color 顏色
     * @return 對象
     */
    public CustomButton setBgDisableColor(int color) {
        this.bgColorDisable = getResources().getColor(color);
        return this;
    }

    /**
     * 設置按下的顏色
     *
     * @param color 顏色
     * @return 對象
     */
    public CustomButton setTextPressedColor(int color) {
        this.textColorPress = getResources().getColor(color);
        return this;
    }

    /**
     * 設置正常的顏色
     *
     * @param color 顏色
     * @return 對象
     */
    public CustomButton setTextNormalColor(int color) {
        this.textColor = getResources().getColor(color);
        return this;
    }

    /**
     * 設置不可點擊的顏色
     *
     * @param color 顏色
     * @return 對象
     */
    public CustomButton setTextDisableColor(int color) {
        this.textColorDisable = getResources().getColor(color);
        return this;
    }

    /**
     * 設置邊框寬度
     *
     * @param strokeWidth 邊框寬度值
     * @return 對象
     */
    public CustomButton setStrokeWidth(int strokeWidth) {
        this.strokeWidth = strokeWidth;
        return this;
    }

    /**
     * 設置邊框顏色
     *
     * @param strokeColor 邊框顏色
     * @return 對象
     */
    public CustomButton setStrokeColor(int strokeColor) {
        this.strokeColor = getResources().getColor(strokeColor);
        return this;
    }


    /**
     * 設置圓角半徑
     *
     * @param radius 半徑
     * @return 對象
     */
    public CustomButton setCornersRadius(float radius) {
        this.cornersRadius = radius;
        return this;
    }

    public CustomButton setRippleColor(int color){
        this.rippleColor = createRippleColorStateList(getResources().getColor(color));
        return this;
    }

    /**
     * 使用shape
     * 所有與shape相關的屬性設置之后調用此方法才生效
     */
    public void use() {
        init();
    }


    /**
     * 單位轉換工具類
     *
     * @param context  上下文對象
     * @param dipValue 值
     * @return 返回值
     */
    private int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

}

在應用主題是md主題的情況下,默認的按鈕是自帶波紋點擊效果的,如果用<ripple/>作為按鈕的background是完全沒問題的,但在自定義的按鈕中設置了按鈕的背景色,波紋效果就會消失,剛開始想不到辦法解決,網上搜索的自定義波紋點擊按鈕都是要自己繪制,稍顯復雜,優點是可以兼容5.0以下的版本。于是只能自己摸索,終于找到了一個簡單方法。<ripple/>標簽最終都會被解析成RippleDrawable,可不可以直接實例化一個RippleDrawable呢,答案是可以的,直接看上面的代碼,主要代碼就這一段:

/**
     * 設置按鈕的Selector
     *
     * @return stateListDrawable
     */
    public Drawable getSelector() {
        StateListDrawable stateListDrawable = new StateListDrawable();
        //注意該處的順序,只要有一個狀態與之相配,背景就會被換掉
        //所以不要把大范圍放在前面了,如果sd.addState(new[]{},normal)放在第一個的話,就沒有什么效果了
        stateListDrawable.addState(new int[]{android.R.attr.state_pressed, android.R.attr.state_enabled}, getDrawable(android.R.attr.state_pressed));
        stateListDrawable.addState(new int[]{-android.R.attr.state_enabled}, getDrawable(-android.R.attr.state_enabled));
        stateListDrawable.addState(new int[]{}, getDrawable(android.R.attr.state_enabled));

        if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.LOLLIPOP) {
            return stateListDrawable;
        }else{

            RippleDrawable rippleDrawable = new RippleDrawable(rippleColor,stateListDrawable,null);
            return rippleDrawable;
        }
    }

在設置按鈕的背景drawable之前,實例化一個RippleDrawable。
第一參數就是波紋顏色;
第二個參數是平時我們設置的按鈕背景selector,如果直接用selector作為背景是沒有波紋點擊效果的,這里直接把xml轉化成StateListDrawable,然后再作為RippleDrawable的content;
第三個參數是控制波紋范圍的drawable,這里直接傳null。
好了,自定義帶波紋效果的Button完成,代碼很簡單,注釋也比較細,就不多解釋了。代碼傳送門

用法

xml方式

app:shape="rectangle" 設置按鈕的形狀,矩形(包括帶圓角的矩形)、圓形、線形、環形(環形一直顯示不對,不知道怎么回事)
app:bgColor="@color/colorPrimary" 按鈕可點擊時的背景色
app:bgColorPress="@color/colorPrimaryDark" 按鈕按下時的背景色
app:bgColorDisable="@color/white" 按鈕不可用時的背景色
app:cornersRadius="20" 當shape為矩形時的圓角角度
app:strokeWidth="10" 邊線寬
app:strokeColor="@color/black" 邊線顏色
app:textColor="@color/white" 按鈕正常狀態時的文字顏色
app:textColorPress="@color/black" 按鈕被按下時的文字顏色
app:textColorDisable="@color/gray" 按鈕不可用時文字顏色
app:rippleColor="@color/colorAccent" 按鈕被觸摸時的波紋顏色
注意自定義命名空間 xmlns:app="http://schemas.android.com/apk/res-auto"

<com.liuqiang.customviewlibrary.CustomButton
            android:id="@+id/customButton"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:text="自定義按鈕(xml設置)"
            android:textColor="@color/white"
            android:textSize="20sp"
            android:gravity="center"

            app:shape="rectangle"
            app:bgColor="@color/colorPrimary"
            app:bgColorPress="@color/colorPrimaryDark"
            app:bgColorDisable="@color/white"
            app:cornersRadius="20"
            app:strokeWidth="10"
            app:strokeColor="@color/black"
            app:textColor="@color/white"
            app:textColorPress="@color/black"
            app:textColorDisable="@color/gray"
            app:rippleColor="@color/colorAccent"
    />

代碼方式

customButton_code = (CustomButton) findViewById(R.id.customButton1);
        customButton_code.setShapeType(CustomButton.RECTANGLE)
                .setBgNormalColor(R.color.colorPrimary)
                .setBgPressedColor(R.color.colorPrimaryDark)
                .setBgDisableColor(R.color.white)
                .setCornersRadius(20)
                .setStrokeColor(R.color.black)
                .setStrokeWidth(10)
                .setTextNormalColor(R.color.white)
                .setTextPressedColor(R.color.black)
                .setTextDisableColor(R.color.gray)
                .setRippleColor(R.color.colorAccent)
                .use();

注意設置完屬性后記得調用use()方法。

總結

如果你也在苦惱按鈕的樣式太多,需要寫大量的<ripple/><shape/>等xml文件,不妨用這種方式,擴展性也非常強,包括顏色漸變、點擊動畫等。歡迎

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,428評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,024評論 3 413
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,285評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,548評論 1 307
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,328評論 6 404
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 54,878評論 1 321
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 42,971評論 3 439
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,098評論 0 286
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,616評論 1 331
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,554評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,725評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,243評論 5 355
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 43,971評論 3 345
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,361評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,613評論 1 280
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,339評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,695評論 2 370

推薦閱讀更多精彩內容