記錄SwitchCompat 屬性,text字體顏色設置

SwitchCompat 控件本身含有屬性

textOn:控件打開時顯示的文字
textOff:控件關閉時顯示的文字
thumb:控件開關的圖片
track:控件開關的軌跡圖片
typeface:設置字體類型
switchMinWidth:開關最小寬度
switchPadding:設置開關 與文字的空白距離
switchTextAppearance:設置文本的風格
checked:設置初始選中狀態
splitTrack:是否設置一個間隙,讓滑塊與底部圖片分隔(API 21及以上)
showText:設置是否顯示開關上的文字(API 21及以上)

這個控件分爲xml配置和java代碼控制
其中xml配置很簡單:

<android.support.v7.widget.SwitchCompat
        android:id="@+id/switch_kt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:switchMinWidth="20dp"
        android:textOn="on"
        style="@style/MySwitchTheme"
        app:showText="true"
        android:textOff="off" />

對應的style配置

  <style name="MySwitchTheme">
        <item name="colorControlActivated">#EF8A33</item>
        <item name="colorSwitchThumbNormal">#FFF1F1F1</item>
        <item name="android:colorForeground">#FF2F2F2F</item>
    </style>

這樣顯示出來的 文字顏色默認是黑色,按鈕未選中是白色,選中後顏色的橘黃色。也就是 第二個屬性。具體屬性意思請百度。

如果要設置text字體顏色,在style文件中添加對應屬性

 <style name="texton" parent="Theme.AppCompat.Light">
        <item name="android:textColor">#ffffff</item>
        <item name="android:textSize">12sp</item>
    </style>

第一個是字體顏色,第二個是字體大小

app:switchTextAppearance="@style/texton"

在上面控件中添加這個屬性,就可以了————》但是這個屬性是單一的text字體顏色,就是從始至終都是白色或者你寫的那個顏色,如何讓選中不同狀態時候顯示不同顏色呢。 簡單 java代碼控制
這裏要用到的屬性是:switchTextAppearance()
style代碼:

  <style name="textoff" parent="Theme.AppCompat.Light">
        <item name="android:textColor">#000000</item>
        <item name="android:textSize">12sp</item>
    </style>
    <style name="texton" parent="Theme.AppCompat.Light">
        <item name="android:textColor">#ffffff</item>
        <item name="android:textSize">12sp</item>
    </style>

具體代碼:

public class MainActivity extends AppCompatActivity {
    private SwitchCompat switchCompat;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        switchCompat=findViewById(R.id.s_v);
         //如果在xml控件中未寫這個屬性,可以在這裏寫,如何寫了可以不用寫
        switchCompat.setChecked(false);
        switchCompat.setSwitchTextAppearance(this,R.style.textoff);
        switchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked){
                    switchCompat.setSwitchTextAppearance(
                            MainActivity.this,R.style.texton);
                }else {
                    switchCompat.setSwitchTextAppearance(MainActivity.this,R.style.textoff);
                }
            }
        });
    }
}

到此結束

發佈了26 篇原創文章 · 獲贊 4 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章