Android開關:Switch控件


 

什么是開關?先看一下Switch的實現效果

和手機上開啟移動數據的按鈕很像

 

 

屬性:

 

  • android:showText:設置on/off的時候是否顯示文字,boolean
  • android:splitTrack:是否設置一個間隙,讓滑塊與底部圖片分隔,boolean
  • android:switchMinWidth:設置開關的最小寬度
  • android:switchPadding:設置滑塊內文字的間隔
  • android:switchTextAppearance:設置開關的文字外觀,暫時沒發現有什么用...
  • android:textOff:按鈕沒有被選中時顯示的文字
  • android:textOn:按鈕被選中時顯示的文字
  • android:textStyle:文字風格,粗體,斜體寫划線那些
  • android:track:底部的圖片
  • android:thumb:滑塊的圖片
  • android:typeface:設置字體

 

使用這個控件比較簡單,只要在布局文件中引用,然后設置相關的屬性就可以了

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" tools:context="com.contentprovide.liuliu.togglebutton_test.MainActivity">


   <Switch android:id="@+id/swh" android:layout_width="wrap_content" android:layout_height="wrap_content" android:track="@drawable/tra" android:thumb="@drawable/a3" android:textOff="off" android:textOn="on"
       />

</LinearLayout>

 

 

 

 

我這里的track和thumb引用的兩個drawable資源文件是我自己定義的

 

tra.xml

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

 

 

a1.xml、a2.xml、a3.xml是自定義圖形,比較簡單,這里就不記錄了

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM