Switch trong Android
Switch là một widget trong android, nó có 2 trạng thái chọn lựa. Nó được sử dụng để hiển thị trạng thái checked và unchecked của một nút thông qua mộ thanh trượt cho người dùng. Nó có 2 Button cơ bản là on/off cho biết trạng thái của Switch. Switch thường được sử dụng hai nút on/off trong trường hợp sau:âm thanh, WiFi, Bluetooth, v.v.
Lớp Switch là lớp con của lớp CompoundButton.
Các phương của Switch
Lớp Switch kế thừa nhiều phương thức của View, TextView hoặc Button
Một vài phương thức thường sử dụng:
Phương thức | Ý nghĩa |
---|---|
public boolean isChecked() | Trạng thái hiện tại của Switch |
public void setChecked(boolean status) | Thay đổi trạng thái của Switch |
Switch code in XML:
<Switch android:id="@+id/simpleSwitch" android:layout_width="wrap_content" android:layout_height="wrap_content"/>
Switch code trong Java
// initiate a Switch Switch simpleSwitch = (Switch) findViewById(R.id.simpleSwitch); // check current state of a Switch (true or false). Boolean switchState = simpleSwitch.isChecked();
Thuộc tính thường dùng của Switch
Bây giờ chúng xem một số thuộc tính hay sử dụng trong Switch trong tập tin XML
1. android:id: Là thuộc tính duy nhất của Switch. Xem ví dụ sau:
<Switch android:id="@+id/simpleSwitch" android:layout_width="wrap_content" android:layout_height="wrap_content"/>
Dựa vào Id ta sẽ lấy được control theo đúng Id này, xem code bên dưới để biết cách lấy control theo Id:
Switch chkSimpleCheckBox= (Switch) findViewById(R.id.simpleSwitch);
2. android:checked: checked là thuộc tính của Switch dùng để set trạng thái của Switch. Giá trị là true hoặc false, nếu giá trị là true thì trạng thái Switch là checked, ngược lại là false thì trạng thái của Switch là unchecked. Chúng ta cũng có thể set trạng thái của Switch bên Java Code bằng cách dùng phương thức setChecked(boolean status). Ví dụ sau chúng ta set android:checked="true"
<Switch android:id="@+id/simpleSwitch" android:layout_width="wrap_content" android:layout_height="wrap_content" android:checked="true"/> <!-- set the current state of the Switch-->
Set thuộc tính checked của Switch trong Java Class
/*Add in Oncreate() funtion after setContentView()*/ // initiate a Switch Switch simpleSwitch = (Switch) findViewById(R.id.simpleSwitch); //set the current state of a Switch simpleSwitch.setChecked(true);
3. android:text: thuộc tính text dùng hiển thị nội dung trong một Switch. Chúng ta có thể set thuộc tính này trong tập tin xml hoặc java code. Ví dụ set android:text="sound"
<Switch android:id="@+id/simpleSwitch" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:text="Sound" /> <!--displayed text of switch-->
Set nội dung của Switch trong Java class:
/*Add in Oncreate() funtion after setContentView()*/ // initiate Switch Switch simpleSwitch = (Switch) findViewById(R.id.simpleSwitch); //displayed text of the Switch simpleSwitch.setText("switch");
4. android:gravity: Thuộc tính này thường sử dụng để canh nội dung trong CheckBox: left, right, center, top, bottom, center_vertical, center_horizontal. Ví dụ chúng ta set android:gravity="left"
<Switch android:id="@+id/simpleSwitch" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Sound" android:checked="true" android:gravity="left"/><!--gravity of the Switch-->
5. android:textOn và android:testOff: thuộc tính textOn được sử dụng để hiển thị câu thông báo khi Switch ở trạng thái checked. Chúng ta có thể set textOn trong XML, hoặc trong Java Class.
Trong ví dụ sau chúng ta sẽ thiết lập android:textOn="Yes" và android:textOff="No"
Thiết lập thuộc tính android:textOn và testOff trong Java class:
/*Add in Oncreate() funtion after setContentView()*/ Switch simpleSwitch = (Switch) findViewById(R.id.simpleSwitch); // initiate Switch simpleSwitch.setTextOn("On"); // displayed text of the Switch whenever it is in checked or on state simpleSwitch.setTextOff("Off"); // displayed text of the Switch whenever it is in unchecked i.e. off state
6. android:textColor: Thuộc tính này dùng xác định màu chữ, dạng màu chữ: “#argb”, "#rgb”, “#rrggbb”, hoặc “#aarrggbb”. Vi dụ sau set nội dung văn bản trong Switch màu đỏ.
<Switch android:id="@+id/simpleSwitch" android:layout_width="wrap_content" android:layout_height="wrap_content" android:checked="true" android:text="switch" android:layout_centerHorizontal="true" android:textOn="On" android:textOff="Off" android:gravity="center" android:textColor="#f00"/><!-- Red color for displayed text-->
Thiết lập thuộc tính màu chữ trong Java Class
/*Add in Oncreate() funtion after setContentView()*/ Switch simpleSwitch = (Switch) findViewById(R.id.simpleSwitch);// initiate Switch simpleSwitch.setTextColor(Color.RED); //red color for displayed text of Switch
7. android:textSize: Thuộc tính textSize xác định kích thước nội dung văn bản của Switch. Chúng ta có thể đặt kích thước văn bản theo: sp(scale independent pixel) hoặc dp(density pixel). Trong ví dụ này chúng ta xác định kich thước cho văn bản là 40sp.
<Switch android:id="@+id/simpleSwitch" android:layout_width="wrap_content" android:layout_height="wrap_content" android:checked="true" android:text="switch" android:layout_centerHorizontal="true" android:textOn="On" android:textOff="Off" android:textColor="#f00" android:gravity="center" android:textSize="40sp"/> <!--25sp displayed text size-->
Thiết lập thuộc tính TextSize trong Java class:
Switch simpleSwitch = (Switch) findViewById(R.id.simpleSwitch); // initiate Switch simpleSwitch.setTextSize(40); // set 25sp displayed text size of Switch
8. android:textStyle: Thuộc tính xác định loại văn bản của Switch, thông thường có các loại văn bản:bold, italic và normal. Nếu chúng ta muốn sử nhiều hơn một loại văn bản thì phải thêm phép toán hoặc "|" vào giữa các loại văn bản. Trong ví dụ sau chúng ta set bold và italic cho chuỗi văn bản của Switch:
<Switch android:id="@+id/simpleSwitch" android:layout_width="wrap_content" android:layout_height="wrap_content" android:checked="false" android:text="switch" android:layout_centerHorizontal="true" android:textOn="On" android:textOff="Off" android:textColor="#f00" android:gravity="center" android:textSize="25sp" android:textStyle="bold|italic"/><!--bold and italic text style for displayed text-->
9. android:background: Thuộc tính này xác định màu nền cho Switch.
<Switch android:id="@+id/simpleSwitch" android:layout_width="wrap_content" android:layout_height="wrap_content" android:checked="true" android:text="switch" android:layout_centerHorizontal="true" android:textOn="On" android:textOff="Off" android:textColor="#f00" android:padding="20dp" android:gravity="center" android:textSize="25sp" android:background="#000"/><!-- black background color-->
Thiết lập thuộc tính Background trong Java class:
Switch simpleSwitch = (Switch) findViewById(R.id.simpleSwitch); simpleSwitch.setBackgroundColor(Color.BLACK);
10. android:padding: Thuộc tính này xác định khoảng cách từ đường viền của Switch với nội dung nó chứa: left, right, top or bottom. Cũng ví dụ trên bây giờ chúng ta xác định padding=10sp từ mọi phía của Switch.
<Switch android:id="@+id/simpleSwitch" android:layout_width="wrap_content" android:layout_height="wrap_content" android:checked="true" android:text="switch" android:layout_centerHorizontal="true" android:textOn="On" android:textOff="Off" android:textColor="#f00" android:gravity="center" android:textSize="25sp" android:padding="40dp"/><!-- 20dp padding from all the side's-->
11. android:drawableBottom, android:drawableTop,android: drawableRight và android:drawableLeft: Các thuộc tính này hiển thị hình trong res/drawable theo các hướng: bottom, top, right và left nội dung văn bản của Switch.
Ví dụ sau thiết lập icon phía dưới nội dung của Switch.
<Switch android:id="@+id/simpleSwitch" android:layout_width="wrap_content" android:layout_height="wrap_content" android:checked="true" android:text="switch" android:layout_centerHorizontal="true" android:textOn="On" android:textOff="Off" android:textColor="#f00" android:gravity="center" android:textSize="25sp" android:drawableBottom="@drawable/ic_launcher"/><!--drawable icon to be displayed in the bottom of text-->
Ví dụ: Trong ví dụ này chúng ta sẽ làm app có 2 Switch và một Button. Khi người sử dụng chọn Switch và click Button sẽ hiện thị trạng thái hiện tại của Switch qua đối tượng TOAST (đối tượng này sẽ học trong những bài sau) . Tiến hành tạo project, vào thư mục res /layout -> activity_main.xml thiết kế giao diện sau:
Bước 1: Tạo một project tên là TextView: File->New->Android Application Project điền các thông tin ->Next ->Finish
Bước 2: Mở res -> layout -> xml (hoặc) activity_main.xml và thêm code, chúng ta sẽ tạo các đối tượng Switch trong Relative Layout.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="hiepsiit.com.switchwitch.MainActivity" > <Switch android:id="@+id/simpleSwitch1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:checked="false" android:text="switch 1" android:textOff="Off" android:textOn="On" /> <Button android:id="@+id/btnSubmit" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/simpleSwitch2" android:layout_below="@+id/simpleSwitch2" android:layout_marginLeft="28dp" android:layout_marginTop="129dp" android:background="#009284" android:padding="10dp" android:text="Submit" android:textColor="#fff" android:textStyle="bold" /> <Switch android:id="@+id/simpleSwitch2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/simpleSwitch1" android:layout_marginTop="88dp" android:checked="true" android:text="switch 2" android:textOff="Off" android:textOn="On" /> </RelativeLayout>
Chuyển quan XML đổi tên các điều khiển:
Điều khiển | android:id | android:text |
---|---|---|
switch1 | simpleSwitch1 | @string/switch1 |
switch2 | simpleSwitch2 | @string/switch2 |
Button1 | btnSubmit | @string/btnsubmit |
Vào thư mục res/values bổ sung string.xml (Chúng ta không khai báo trực tiếp nhãn vào các điều khiển, mà thông qua string.xml)
<resources> <string name="app_name">SwitchWidget</string> <string name="hello_world">Hello world!</string> <string name="action_settings">Settings</string> <string name="switch1">Switch 1</string> <string name="switch2">Switch 2</string> <string name="btnsubmit">Submit</string> </resources>
Bước 3: Mở app -> src ->MainActivity.java và thêm code. Khi click vào Submit sẽ lấy trạng thái của Switch, sau đó dùng đối tượng TOAST để hiển thị.
package hiepsiit.com.switchwitch; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Switch; import android.widget.Toast; public class MainActivity extends Activity { Switch simpleSwitch1, simpleSwitch2; Button submit; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); simpleSwitch1 = (Switch) findViewById(R.id.simpleSwitch1); simpleSwitch2 = (Switch) findViewById(R.id.simpleSwitch2); submit = (Button) findViewById(R.id.btnSubmit); submit.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { String statusSwitch1, statusSwitch2; if (simpleSwitch1.isChecked()) statusSwitch1 = simpleSwitch1.getTextOn().toString(); else statusSwitch1 = simpleSwitch1.getTextOff().toString(); if (simpleSwitch2.isChecked()) statusSwitch2 = simpleSwitch2.getTextOn().toString(); else statusSwitch2 = simpleSwitch2.getTextOff().toString(); Toast.makeText(getApplicationContext(), "Switch1 :" + statusSwitch1 + "\n" + "Switch2 :" + statusSwitch2, Toast.LENGTH_LONG).show(); // display the current state for switch's } }); } }
Ứng dụng này được phát triển bởi adt bundle, android 4.2 sử dụng minimum sdk 14 and target sdk 21.
Kết quả khi chạy ứng dụng:
Sau đó Click Button submit:
Cập nhật công nghệ từ Youtube tại link: https://www.youtube.com/channel/UCOxeYcvZPGf-mGLYSl_1LuA/videos
Để tham gia khóa học công nghệ truy cập link: http://thuvien.hocviendaotao.com
Mọi hỗ trợ về công nghệ email: dinhanhtuan68@gmail.com