Android使用Java代碼設置selector或drawable,以及使用自定義控件方式使用它

鎮樓圖~~!
這裏寫圖片描述
TextView再給個selecotor 這種東西不要太簡單,但是這種東西我不想重複去寫N個Selector ! so~

  /**
     * 獲取Selector
     * @param normalDraw
     * @param pressedDraw
     * @return
     */
    public static StateListDrawable getSelector(Drawable normalDraw, Drawable pressedDraw) {
        StateListDrawable stateListDrawable  = new StateListDrawable();
        stateListDrawable.addState(new int[]{ android.R.attr.state_pressed }, pressedDraw);
        stateListDrawable.addState(new int[]{ }, normalDraw);
        return stateListDrawable ;
    }

    /**
     * 設置shape(設置單獨圓角)
     * @param topLeftCA
     * @param topRigthCA
     * @param buttomLeftCA
     * @param buttomRightCA
     * @param bgColor
     * @param storkeWidth
     * @param strokeColor
     * @return
     */
    public GradientDrawable getDrawable(float topLeftCA, float topRigthCA, float buttomLeftCA,
                                        float buttomRightCA, int bgColor, int storkeWidth, int strokeColor) {
        //把邊框值設置成dp對應的px
        storkeWidth = dp2px(this.mContext, storkeWidth);

        float[] circleAngleArr = {topLeftCA, topLeftCA, topRigthCA, topRigthCA,
                buttomLeftCA, buttomLeftCA, buttomRightCA, buttomRightCA};
        //把圓角設置成dp對應的px
        for (int i = 0; i < circleAngleArr.length; i++){
            circleAngleArr[i] = dp2px(this.mContext, circleAngleArr[i]);
        }

        GradientDrawable gradientDrawable = new GradientDrawable();
        gradientDrawable.setCornerRadii(circleAngleArr);//圓角
        gradientDrawable.setColor(bgColor); //背景色
        gradientDrawable.setStroke(storkeWidth, strokeColor); //邊框寬度,邊框顏色

        return gradientDrawable;
    }

    /**
     * 設置shape(圓角)
     *
     * @param bgCircleAngle
     * @param bgColor
     * @param width
     * @param strokeColor
     * @return
     */
    public GradientDrawable getDrawable(int bgCircleAngle, int bgColor, int width, int strokeColor) {
        GradientDrawable gradientDrawable = new GradientDrawable();
        gradientDrawable.setCornerRadius(bgCircleAngle);
        gradientDrawable.setColor(bgColor);
        gradientDrawable.setStroke(width, strokeColor);
        return gradientDrawable;
    }

這裏就不多說了,跟用xml設置Selector的步驟是一樣的
值得注意的是:

getSelector();中

 stateListDrawable.addState(new int[]{ android.R.attr.state_pressed }, pressedDraw);

這段在設置值的時候前後要給空格,否則這個按下的狀態會設置不上去,具體原因這裏就不深究了。
在getDrawable有兩個方法,一個是設置矩形所有角的弧度(radius),一個是單獨設置每一個角的弧度(topLeftRadius,topRightRadius,bottomLeftRadius,bottomRightRadius)

 gradientDrawable.setCornerRadii(circleAngleArr);//圓角

這個方法需要傳入一個有8個值的float數組,(開始沒想明白,後來翻了翻源碼,每一個角對應2個值,一個x一個y,好吧~高中數學都還給老師了,一個值怎麼畫弧線呢 - -!~)

    /**
     * <p>Specify radii for each of the 4 corners. For each corner, the array
     * contains 2 values, <code>[X_radius, Y_radius]</code>. The corners are ordered
     * top-left, top-right, bottom-right, bottom-left. This property
     * is honored only when the shape is of type {@link #RECTANGLE}.</p>
     * <p><strong>Note</strong>: changing this property will affect all instances
     * of a drawable loaded from a resource. It is recommended to invoke
     * {@link #mutate()} before changing this property.</p>
     *
     * @param radii 4 pairs of X and Y radius for each corner, specified in pixels.
     *              The length of this array must be >= 8
     *
     * @see #mutate()
     * @see #setCornerRadii(float[])
     * @see #setShape(int)
     */
    public void setCornerRadii(float[] radii) {
        mGradientState.setCornerRadii(radii);
        mPathIsDirty = true;
        invalidateSelf();
    }

代碼註釋寫的很清楚了我就不拿我的三級英語來扯了···

使用:
如果只想添加個圓角背景那麼可以這樣

     GradientDrawable gradientDrawable = SelectorUtils.getInstance(this)
                .getDrawable(20, ContextCompat.getColor(this, R.color.bisque), 2, ContextCompat.getColor(this, R.color.aqua));
        editText.setBackground(gradientDrawable);

如果是Selector

       GradientDrawable normalDraw = SelectorUtils.getInstance(this)
                .getDrawable(20, ContextCompat.getColor(this, R.color.aliceblue), 2, ContextCompat.getColor(this, R.color.blueviolet));
        GradientDrawable pressDraw = SelectorUtils.getInstance(this)
               .getDrawable(20, ContextCompat.getColor(this, R.color.brown), 2, ContextCompat.getColor(this, R.color.colorPrimaryDark));

        StateListDrawable stateListDrawable = SelectorUtils.getSelector(normalDraw, pressDraw);
        textView.setBackground(stateListDrawable);

如果想單獨設置每個角的弧度可以這樣:

GradientDrawable normalDraw1 = SelectorUtils.getInstance(this)
                .getDrawable(10,20,0,40, ContextCompat.getColor(this, R.color.chocolate), 2, ContextCompat.getColor(this, R.color.darkcyan));
        GradientDrawable pressDraw1 = SelectorUtils.getInstance(this)
                .getDrawable(10, 10, 0, 0, ContextCompat.getColor(this, R.color.darkgoldenrod), 2, ContextCompat.getColor(this, R.color.darkorchid));

        StateListDrawable stateListDrawable1 = SelectorUtils.getSelector(normalDraw1,pressDraw1);
        textView1.setBackground(stateListDrawable1);

如果使用selector最後記得設置點擊事件:

  tvText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

如果不設置點擊事件,按下的drawable不會顯示,原因是點擊事件未分發,這裏不過多解釋。

是不是省去了很多selector或者drawable文件~~ 最近一直想寫一個自定義控件,so~~
先來張效果圖:
這裏寫圖片描述
使用:

 <speedytextview.fmr.com.spdtvlibrary.SpdTextView
            android:id="@+id/spd5"
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:layout_marginTop="10dp"
            android:gravity="center"
            android:padding="10dp"
            android:text="方某人"
            android:textSize="16.0sp"
            app:bgClickColor="@color/yellow"
            app:bgColor="@color/aqua"
            app:buttomLeftCA="30dp"
            app:buttomRightCA="40dp"
            app:normalStorkeColor="@color/cadetblue"
            app:normalStorkeWidth="2dp"
            app:pressStorkeColor="@color/cornflowerblue"
            app:pressStorkeWidth="2dp"
            app:topLeftCA="10dp"
            app:topRightCA="20dp" />

這裏需要注意下,bgColor這條屬性是必須設置的,否則背景色是透明的~~原諒我的設置了默認值 - -!~ 屬性這裏就不多介紹了,源碼都有註釋(雖然是我自己寫的,但是每次用的時候都要去看自己寫的註釋~)。

經常用一些牛逼的第三方庫 免不了想給自己來一波高大上的調用 so~~
你還可以這樣用:

      ((SpdTextView)findViewById(R.id.spd6))
                .setBgColor(ContextCompat.getColor(this, R.color.darkorchid))
                .setBgClickColor(ContextCompat.getColor(this, R.color.brown))
                .setNormalStorkeWidth(5)
                .setNormalStorkeColor(ContextCompat.getColor(this, R.color.burlywood))
                .setPressStorkeWidth(2)
                .setPressStorkeColor(ContextCompat.getColor(this, R.color.antiquewhite))
                .setBgCircleAngle(40)
                .build();

引入:

compile 'com.fmr:speedytextview:1.0.0'

源碼

好吧 裝逼結束 最後打上註釋

//                            _ooOoo_  
//                           o8888888o  
//                           88" . "88  
//                           (| -_- |)  
//                            O\ = /O  
//                        ____/`---'\____  
//                      .   ' \\| |// `.  
//                       / \\||| : |||// \  
//                     / _||||| -:- |||||- \  
//                       | | \\\ - /// | |  
//                     | \_| ''\---/'' | |  
//                      \ .-\__ `-` ___/-. /  
//                   ___`. .' /--.--\ `. . __  
//                ."" '< `.___\_<|>_/___.' >'"".  
//               | | : `- \`.;`\ _ /`;.`/ - ` : | |  
//                 \ \ `-. \_ __\ /__ _/ .-` / /  
//         ======`-.____`-.___\_____/___.-`____.-'======  
//                            `=---='  
//  
//         .............................................  
//                  佛祖保佑             永無BUG 
//          佛曰:  
//                  寫字樓裏寫字間,寫字間裏程序員;  
//                  程序人員寫程序,又拿程序換酒錢。  
//                  酒醒只在網上坐,酒醉還來網下眠;  
//                  酒醉酒醒日復日,網上網下年復年。  
//                  但願老死電腦間,不願鞠躬老闆前;  
//                  奔馳寶馬貴者趣,公交自行程序員。  
//                  別人笑我忒瘋癲,我笑自己命太賤;  
//                  不見滿街漂亮妹,哪個歸得程序員?  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章