狀態開關(ToggleButton):
常用屬性:isChecked(是否被選中,如true)
監聽:1.監聽方法:setOnCheckedChangeListener
2.監聽器:CompoundButton.OnCheckedChangeListener
1.Activity
//狀態的開關 public class ToggleButtonActivity extends Activity {private ToggleButton toggleButton;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.toggle_button);toggleButton = (ToggleButton)findViewById(R.id.toggleButtonId);toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {if(isChecked){Toast.makeText(ToggleButtonActivity.this, "無線網絡打開了!", Toast.LENGTH_SHORT).show();}else{Toast.makeText(ToggleButtonActivity.this, "無線網絡關閉了!", Toast.LENGTH_SHORT).show();}}});} }
2.xml文件
<?xml version="1.0" encoding="utf-8"?> <!-- 狀態的開關頁面 --> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="horizontal"android:padding="5dp" ><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="無線網:"android:textSize="20sp" /><ToggleButtonandroid:id="@+id/toggleButtonId"android:layout_width="wrap_content"android:layout_height="wrap_content" /></LinearLayout>
3.效果顯示圖