介紹一下Android組件裡面的RadioButton單選按鈕與CheckBox復選框的使用,並且怎麼監聽其狀態;
RadioButton選項按鈕可用於多選一的應用中,如果想在選中莫一個選項按鈕後,其它的選項按鈕都被設未選中狀態,需將RadioButton標簽放在RadioGroup標簽中。
例如:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical" >
-
- <TextView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="Radio Demo" />
-
- <RadioGroup
- android:id="@+id/sexRg"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:checkedButton="@+id/female"
- android:orientation="vertical" >
-
- <RadioButton
- android:id="@id/female"
- android:text="女" />
-
- <RadioButton
- android:id="@+id/male"
- android:text="男" />
- </RadioGroup>
-
-
- </LinearLayout>
在模擬器中效果:
在代碼中監聽單選框狀態,
- package cn.class3g.activity;
-
- import android.app.Activity;
- import android.os.Bundle;
- import android.util.Log;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.RadioButton;
- import android.widget.RadioGroup;
- import android.widget.RadioGroup.OnCheckedChangeListener;
-
- public class RadioDemo extends Activity implements
- OnCheckedChangeListener {
-
- RadioGroup rg = null;
- private static final String TAG = "TAG";
-
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.radio_layout);
-
- findViews();
-
- // 指定某個選項被選中
- rg.check(R.id.male);
-
- // 獲取當前選項組中被選中的選項的id
- int checkedId = rg.getCheckedRadioButtonId();
- RadioButton rb = (RadioButton) this.findViewById(checkedId);
- Log.i(TAG, rb.getText().toString());//通過日志打印出被選中的選項
- }
-
- private void findViews() {
- rg = (RadioGroup) this.findViewById(R.id.sexRg);
- // 注冊監聽器
- rg.setOnCheckedChangeListener(this);
- }
-
- // 覆蓋OnCheckedChangeListener接口的抽象方法
- public void onCheckedChanged(RadioGroup group, int checkedId) {
- if (group.getId() == R.id.sexRg) {
- RadioButton rb = (RadioButton) this.findViewById(checkedId);
- Log.i(TAG, rb.getText().toString());//用日志打印出被選中的選項
- }
-
- }
-
- }
每點擊一次都會通過日志輸出,效果: