•任務
•屬性
android:track:底部的圖片(灰->綠)
android:thumb:設置 Switch 上面滑動的滑塊,也就是上圖中的白色圓形滑塊
•switch_thumb
點擊 app/src/res 找到 drawable 文件夾,右擊->New->Drawable Resource File;
在該文件中添加如下代碼:
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval"> <size android:width="40dp" android:height="40dp"/> <solid android:color="@color/white"/> </shape>該代碼完成了上圖中白色的圓圈部分。
•switch_track
接着新建一個 Drawable Resource File 文件。
在該文件下添加如下代碼:
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_checked="false"> <shape android:shape="rectangle"> <solid android:color="@color/gray"/> <corners android:radius="30dp"/> </shape> </item> <item android:state_checked="true"> <shape android:shape="rectangle"> <solid android:color="@color/green"/> <corners android:radius="30dp"/> </shape> </item> </selector>@color/gray 和 @color/green 我定義在了 color 下,分別代表灰色和綠色。
- android:state_checked="false" : 定義了 Switch 在未點擊狀態下的界面顯示效果,灰色的圓角矩形
- android:state_checked="true" : 定義了 Switch 再點擊狀態下的界面顯示效果,綠色的圓角矩形
•main_activity.xml
修改 main_activity.xml 代碼,如下所示:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="10dp" android:background="@color/teal_700"> <ImageView android:id="@+id/mImgView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_centerInParent="true"/> <Switch android:id="@+id/mSwitch" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:textOn="開燈" android:textOff="關燈" android:showText="true" android:thumb="@drawable/switch_thumb" android:track="@drawable/switch_track" /> </RelativeLayout>我在該布局中放置了兩個控件:ImageView 和 Switch,其中 ImageViewe 用於放置燈泡;
•為 Switch 設置點擊事件
修改 MainActivity.java 中的代碼,如下所示:
public class SwitchActivity extends AppCompatActivity { private Switch mSwitch; private ImageView mImgView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_switch); mSwitch = findViewById(R.id.mSwitch); mImgView = findViewById(R.id.mImgView); mImgView.setImageResource(R.drawable.take_off); mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { mImgView.setImageResource(isChecked ? R.drawable.take_on:R.drawable.take_off); } }); } }通過 findViewById() 找到 mSwitch 和 mImgView 對應的控件;
然后,對 mSwitch 設置點擊事件 mSwitch.setOnCheckedChangeListener ;
然后通過 isChecked 這個變量判斷 Switch 處於何種狀態:
- isChecked = true : 為 ImageView 設置 take_on 圖片
- isChecked = false : 為 ImageView 設置 take_off 圖片
take_on 和 take_off 是我從網上下載的圖標,我放在了 drawable 文件夾下:
![]()