[Android菜鳥筆記2019.03.15]RadioButtom組件仿微信底部導航切換+drawableTop定製圖片大小

先看效果圖:
在這裏插入圖片描述
█實現點擊切換效果
RadioButtom需要用單擊按鈕組RadioGroup包括,設置3個RadiooButtom的id屬性(不然會選擇多個按鈕),drawableTop設置按鈕圖片和text的drawable_selector選擇狀態資源,用於按下/未選擇時顯示對應顏色。
在這裏插入圖片描述
home_selector:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/home_1_normal_878787"
          android:state_checked="false"/>
    <item android:drawable="@drawable/home_2_enble_21c10c"
          android:state_checked="true"/>
</selector>

buttomcolor_selector:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:color="#21c10c"/>
    <item android:state_checked="false" android:color="#878787"/>
</selector>

RadioButtom調用selector並設定home爲默認展示:

 android:drawableTop="@drawable/home_selector"
 android:textColor="@drawable/buttomcolor_selector"
 android:checked="true"

█自由定製drawableTop屬性
問題來了,由於圖片尺寸不盡可能適配View大小,在一些設備中drawableTop圖片會顯示過大,通過實例化drawable類獲取圖片,重新繪製圖片位置及大小。
優化前:
在這裏插入圖片描述
Main_Ativity中實現:

rgGroup = (RadioGroup) findViewById(R.id.rb_btn);
        home_btn = (RadioButton) findViewById(R.id.home_btn);
        order_btn = (RadioButton) findViewById(R.id.order_btn);
        personal_btn = (RadioButton) findViewById(R.id.personal_btn);

        //定義底部標籤圖片大小
        Drawable drawableWeiHui = getResources().getDrawable(R.drawable.home_selector);
        drawableWeiHui.setBounds(0, 2, 60, 60);//第一0是距左右邊距離,第二0是距上下邊距離,第三69長度,第四寬度
        home_btn.setCompoundDrawables(null, drawableWeiHui, null, null);//只放上面

        Drawable drawableAdd = getResources().getDrawable(R.drawable.order_selector);
        drawableAdd.setBounds(0, 3, 60, 60);
        order_btn.setCompoundDrawables(null,drawableAdd, null, null);

        Drawable drawableRight = getResources().getDrawable(R.drawable.personal_selector);
        drawableRight.setBounds(0, 3, 60,60);
        personal_btn.setCompoundDrawables(null, drawableRight, null, null);

        //初始化底部標籤
        rgGroup.check(R.id.home_btn);

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章