歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android組件之Radio與CheckBox

Android組件之Radio與CheckBox

日期:2017/3/1 10:47:02   编辑:Linux編程
介紹一下Android組件裡面的RadioButton單選按鈕與CheckBox復選框的使用,並且怎麼監聽其狀態;

RadioButton選項按鈕可用於多選一的應用中,如果想在選中莫一個選項按鈕後,其它的選項按鈕都被設未選中狀態,需將RadioButton標簽放在RadioGroup標簽中。

例如:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="fill_parent"
  4. android:layout_height="fill_parent"
  5. android:orientation="vertical" >
  6. <TextView
  7. android:layout_width="fill_parent"
  8. android:layout_height="wrap_content"
  9. android:text="Radio Demo" />
  10. <RadioGroup
  11. android:id="@+id/sexRg"
  12. android:layout_width="fill_parent"
  13. android:layout_height="wrap_content"
  14. android:checkedButton="@+id/female"
  15. android:orientation="vertical" >
  16. <RadioButton
  17. android:id="@id/female"
  18. android:text="女" />
  19. <RadioButton
  20. android:id="@+id/male"
  21. android:text="男" />
  22. </RadioGroup>
  23. </LinearLayout>
在模擬器中效果:




在代碼中監聽單選框狀態,

  1. package cn.class3g.activity;
  2. import android.app.Activity;
  3. import android.os.Bundle;
  4. import android.util.Log;
  5. import android.view.View;
  6. import android.view.View.OnClickListener;
  7. import android.widget.Button;
  8. import android.widget.RadioButton;
  9. import android.widget.RadioGroup;
  10. import android.widget.RadioGroup.OnCheckedChangeListener;
  11. public class RadioDemo extends Activity implements
  12. OnCheckedChangeListener {
  13. RadioGroup rg = null;
  14. private static final String TAG = "TAG";
  15. public void onCreate(Bundle savedInstanceState) {
  16. super.onCreate(savedInstanceState);
  17. setContentView(R.layout.radio_layout);
  18. findViews();
  19. // 指定某個選項被選中
  20. rg.check(R.id.male);
  21. // 獲取當前選項組中被選中的選項的id
  22. int checkedId = rg.getCheckedRadioButtonId();
  23. RadioButton rb = (RadioButton) this.findViewById(checkedId);
  24. Log.i(TAG, rb.getText().toString());//通過日志打印出被選中的選項
  25. }
  26. private void findViews() {
  27. rg = (RadioGroup) this.findViewById(R.id.sexRg);
  28. // 注冊監聽器
  29. rg.setOnCheckedChangeListener(this);
  30. }
  31. // 覆蓋OnCheckedChangeListener接口的抽象方法
  32. public void onCheckedChanged(RadioGroup group, int checkedId) {
  33. if (group.getId() == R.id.sexRg) {
  34. RadioButton rb = (RadioButton) this.findViewById(checkedId);
  35. Log.i(TAG, rb.getText().toString());//用日志打印出被選中的選項
  36. }
  37. }
  38. }
每點擊一次都會通過日志輸出,效果:


Copyright © Linux教程網 All Rights Reserved