RadioButton兼容問題修復(fù)&實現(xiàn)選中縮放動畫

一個帶縮放動畫的 RadioButton

效果如圖

fixedAnimatedRadioButton.gif

How do I use it?

Step 1.Add it in your root build.gradle at the end of repositories:

allprojects {
    repositories {
        ...
        maven { url 'https://jitpack.io' }
    }
}

Step 2. Add the dependency

dependencies {
         implementation 'com.github.qingyc:FixedAnimatedRadioButton:0.1'
}

一.處理低版本RadioButton問題

RadioButton在布局中的使用


    <RadioGroup
        android:id="@+id/rg_main"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:background="@drawable/bg_main_bottom"
        android:gravity="bottom"
        android:orientation="horizontal"
        android:paddingTop="4dp"
        android:paddingBottom="4dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/main_viewpager">

        <com.qingyc.fixedanimatedradiobutton.FixedAnimatedRadioButton
            android:id="@+id/rb_capricorn"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:button="@null"
            android:checked="true"
            android:drawableTop="@drawable/main_rb_01"
            android:gravity="center"
            android:text="@string/capricorn"
            android:textColor="@color/radio_btn_text_color"
            android:textSize="12sp"/>


        <com.qingyc.fixedanimatedradiobutton.FixedAnimatedRadioButton
            android:id="@+id/rb_compatibility"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:button="@null"
            android:checked="false"
            android:drawableTop="@drawable/main_rb_02"
            android:gravity="center"
            android:text="@string/compatibility"
            android:textColor="@color/radio_btn_text_color"
            android:textSize="12sp"/>


        <com.qingyc.fixedanimatedradiobutton.FixedAnimatedRadioButton
            android:id="@+id/rb_personality"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:button="@null"
            android:checked="false"
            android:drawableTop="@drawable/main_rb_03"
            android:gravity="center"
            android:text="@string/personality"
            android:textColor="@color/radio_btn_text_color"
            android:textSize="12sp"/>

        <com.qingyc.fixedanimatedradiobutton.FixedAnimatedRadioButton
            android:id="@+id/rb_discover"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:button="@null"
            android:checked="false"
            android:drawableTop="@drawable/main_rb_04"
            android:gravity="center"
            android:text="@string/discover"
            android:textColor="@color/radio_btn_text_color"
            android:textSize="12sp"/>


    </RadioGroup>

RadioButton在低版本上的問題(android 4.4)

可以看出在低版本的模擬器中 radioButton左邊顯示了一個默認button圖標,xml中 android:button="@null" 無效

android api 19

而在高版本的模擬器和手機中 顯示正常

android api 28

RadioButton的button圖標的設(shè)置是在CompoundButton類中實現(xiàn)的

android Api 28源碼

    public CompoundButton(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);

        final TypedArray a = context.obtainStyledAttributes(
                attrs, com.android.internal.R.styleable.CompoundButton, defStyleAttr, defStyleRes);

        final Drawable d = a.getDrawable(com.android.internal.R.styleable.CompoundButton_button);
        if (d != null) {
            setButtonDrawable(d);
        }

        if (a.hasValue(R.styleable.CompoundButton_buttonTintMode)) {
            mButtonTintMode = Drawable.parseTintMode(a.getInt(
                    R.styleable.CompoundButton_buttonTintMode, -1), mButtonTintMode);
            mHasButtonTintMode = true;
        }

        if (a.hasValue(R.styleable.CompoundButton_buttonTint)) {
            mButtonTintList = a.getColorStateList(R.styleable.CompoundButton_buttonTint);
            mHasButtonTint = true;
        }

        final boolean checked = a.getBoolean(
                com.android.internal.R.styleable.CompoundButton_checked, false);
        setChecked(checked);
        mCheckedFromResource = true;

        a.recycle();

        applyButtonTint();
    }

a.getDrawable(com.android.internal.R.styleable.CompoundButton_button); 獲取xml中設(shè)置的button drawable,CompoundButton內(nèi)部私有成員變量 mButtonDrawable 即是

可以看出最終會調(diào)用下面兩個方法


    /**
     * Sets a drawable as the compound button image given its resource
     * identifier.
     *
     * @param resId the resource identifier of the drawable
     * @attr ref android.R.styleable#CompoundButton_button
     */
    public void setButtonDrawable(@DrawableRes int resId) {
        final Drawable d;
        if (resId != 0) {
            d = getContext().getDrawable(resId);
        } else {
            d = null;
        }
        setButtonDrawable(d);
    }

    /**
     * Sets a drawable as the compound button image.
     *
     * @param drawable the drawable to set
     * @attr ref android.R.styleable#CompoundButton_button
     */
    public void setButtonDrawable(@Nullable Drawable drawable) {
        if (mButtonDrawable != drawable) {
            if (mButtonDrawable != null) {
                mButtonDrawable.setCallback(null);
                unscheduleDrawable(mButtonDrawable);
            }

         mButtonDrawable = drawable

            if (drawable != null) {
                drawable.setCallback(this);
                drawable.setLayoutDirection(getLayoutDirection());
                if (drawable.isStateful()) {
                    drawable.setState(getDrawableState());
                }
                drawable.setVisible(getVisibility() == VISIBLE, false);
                setMinHeight(drawable.getIntrinsicHeight());
                applyButtonTint();
            }
        }
    }
    

可以看出不管是在xml 或者代碼中設(shè)置RadioButton的button 最終都調(diào)用 setButtonDrawable(@Nullable Drawable drawable)

對比Android api 19源碼

點擊查看


    public void setButtonDrawable(Drawable d) {
        if (d != null) {
            if (mButtonDrawable != null) {
                mButtonDrawable.setCallback(null);
                unscheduleDrawable(mButtonDrawable);
            }
            d.setCallback(this);
            d.setVisible(getVisibility() == VISIBLE, false);
            mButtonDrawable = d;
            setMinHeight(mButtonDrawable.getIntrinsicHeight());
        }

        refreshDrawableState();
    }

可以看出 輸入drawable為null時根本沒有調(diào)用 mButtonDrawable = drawable 把mButtonDrawable置空

問題處理

  override fun setButtonDrawable(buttonDrawable: Drawable?) {
             // QTIP: 2019-04-28 修復(fù)低版本(android4.4)設(shè)置按鈕為null時顯示默認按鈕
             if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
                 try {
                     val clazz = CompoundButton::class.java
                     val field = clazz.getDeclaredField("mButtonDrawable")
                     field.isAccessible = true
                     field.set(this, null)
                 } catch (e: Exception) {
                     e.printStackTrace()
                 }
             } else {
                 super.setButtonDrawable(buttonDrawable)
             }
  }

二 實現(xiàn)點擊RadioButton縮放動畫

調(diào)用時機 check狀態(tài)變化時


    override fun setChecked(checked: Boolean) {
        super.setChecked(checked)
        if (width == 0 || height == 0) {
            return
        }
        if (checked) {
            val animator = ValueAnimator.ofFloat(minScaleRate, maxScaleRate)
            animator.addUpdateListener(this)
            animator.duration = 300
            animator.start()
        } else {
            if (animatedScaleRate != 1f) {
                val animator = ValueAnimator.ofFloat(animatedScaleRate, 1f)
                animator.addUpdateListener(this)
                animator.duration = 0
                animator.start()
            }
        }
    }

RadioButton選中動畫實現(xiàn)

   override fun onAnimationUpdate(animation: ValueAnimator?) {
        animatedScaleRate = animation?.animatedValue as Float
        try {
            //1.保存圖標默認位置
            if (mDefaultDrawableBounds == null) {
                mDefaultDrawableBounds = arrayOfNulls(4)
                compoundDrawables.forEachIndexed { index, drawable ->
                    drawable?.let {
                        val rect = Rect(drawable.bounds)
                        mDefaultDrawableBounds?.set(index, rect)
                    }
                }
            }
            var leftDrawable: Drawable? = null
            var rightDrawable: Drawable? = null
            var topDrawable: Drawable? = null
            var bottomDrawable: Drawable? = null
            //2.獲取radioButton中設(shè)置的圖標的drawable
            compoundDrawables.forEachIndexed { index, drawable ->
                drawable?.let {
                    mDefaultDrawableBounds?.get(index)?.let { mDefaultDrawableBounds ->
                        val copyBounds = Rect(mDefaultDrawableBounds)
                        //3.動態(tài)縮放RadioButton的圖標
                        copyBounds.let {
                            copyBounds.left = mDefaultDrawableBounds.left
                            copyBounds.right =
                                mDefaultDrawableBounds.right - (mDefaultDrawableBounds.width() * (1 - animatedScaleRate)).toInt()
                            copyBounds.top =
                                mDefaultDrawableBounds.top + (mDefaultDrawableBounds.height() * (1 - animatedScaleRate)).toInt() / 2
                            copyBounds.bottom =
                                mDefaultDrawableBounds.bottom - (mDefaultDrawableBounds.height() * (1 - animatedScaleRate)).toInt() / 2
                            when (index) {
                                0 -> {
                                    leftDrawable = drawable
                                    leftDrawable?.bounds = copyBounds

                                }
                                1 -> {
                                    topDrawable = drawable
                                    topDrawable?.bounds = copyBounds
                                }
                                2 -> {
                                    rightDrawable = drawable
                                    rightDrawable?.bounds = copyBounds
                                }
                                3 -> {
                                    bottomDrawable = drawable
                                    bottomDrawable?.bounds = copyBounds
                                }
                            }
                        }
                    }
                }
            }
            //4.更新圖標大小和位置
            setCompoundDrawables(leftDrawable, topDrawable, rightDrawable, bottomDrawable)

        } catch (e: Exception) {
        }
    }

github源碼

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子增拥,更是在濱河造成了極大的恐慌毅访,老刑警劉巖糖赔,帶你破解...
    沈念sama閱讀 216,591評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件慌洪,死亡現(xiàn)場離奇詭異株憾,居然都是意外死亡,警方通過查閱死者的電腦和手機计技,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,448評論 3 392
  • 文/潘曉璐 我一進店門喜德,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人垮媒,你說我怎么就攤上這事舍悯。” “怎么了睡雇?”我有些...
    開封第一講書人閱讀 162,823評論 0 353
  • 文/不壞的土叔 我叫張陵萌衬,是天一觀的道長。 經(jīng)常有香客問我它抱,道長秕豫,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,204評論 1 292
  • 正文 為了忘掉前任观蓄,我火速辦了婚禮混移,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘侮穿。我一直安慰自己歌径,他們只是感情好,可當我...
    茶點故事閱讀 67,228評論 6 388
  • 文/花漫 我一把揭開白布亲茅。 她就那樣靜靜地躺著回铛,像睡著了一般。 火紅的嫁衣襯著肌膚如雪克锣。 梳的紋絲不亂的頭發(fā)上茵肃,一...
    開封第一講書人閱讀 51,190評論 1 299
  • 那天,我揣著相機與錄音娶耍,去河邊找鬼免姿。 笑死,一個胖子當著我的面吹牛榕酒,可吹牛的內(nèi)容都是我干的胚膊。 我是一名探鬼主播故俐,決...
    沈念sama閱讀 40,078評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼紊婉!你這毒婦竟也來了药版?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,923評論 0 274
  • 序言:老撾萬榮一對情侶失蹤喻犁,失蹤者是張志新(化名)和其女友劉穎槽片,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體肢础,經(jīng)...
    沈念sama閱讀 45,334評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡还栓,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,550評論 2 333
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了传轰。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片剩盒。...
    茶點故事閱讀 39,727評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖慨蛙,靈堂內(nèi)的尸體忽然破棺而出辽聊,到底是詐尸還是另有隱情,我是刑警寧澤期贫,帶...
    沈念sama閱讀 35,428評論 5 343
  • 正文 年R本政府宣布彼水,位于F島的核電站懒震,受9級特大地震影響从铲,放射性物質(zhì)發(fā)生泄漏靶庙。R本人自食惡果不足惜贴膘,卻給世界環(huán)境...
    茶點故事閱讀 41,022評論 3 326
  • 文/蒙蒙 一恨诱、第九天 我趴在偏房一處隱蔽的房頂上張望拔恰。 院中可真熱鬧话侄,春花似錦、人聲如沸敛瓷。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,672評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽呐籽。三九已至,卻和暖如春蚀瘸,著一層夾襖步出監(jiān)牢的瞬間狡蝶,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,826評論 1 269
  • 我被黑心中介騙來泰國打工贮勃, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留贪惹,地道東北人。 一個月前我還...
    沈念sama閱讀 47,734評論 2 368
  • 正文 我出身青樓寂嘉,卻偏偏與公主長得像奏瞬,于是被迫代替她去往敵國和親枫绅。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,619評論 2 354

推薦閱讀更多精彩內(nèi)容