Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android RadioGroup 單選組用法實例詳解

編輯:關於 Android 程式設計

本文以實例講解 Android 中 RadioGroup 的用法,供需要的朋友參考。

RadioGroup 在需要「多選一」的情境下非常好用,它能將多個 RadioButton 組織成一個單選群組,同一時間只會有一個選項被選中。

MainActivity.java

 package com.example.lesson16_radio; import android.app.Activity; import android.os.Bundle; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Toast; public class MainActivity extends Activity { private RadioGroup group_temo; private RadioButton checkRadioButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); group_temo = (RadioGroup) findViewById(R.id.radioGroup1); // 改變默認選項 group_temo.check(R.id.radio1); // 獲取默認被被選中值 checkRadioButton = (RadioButton) group_temo.findViewById(group_temo .getCheckedRadioButtonId()); Toast.makeText(this, "默認的選項的值是:" + checkRadioButton.getText(), Toast.LENGTH_LONG).show(); // 注冊事件 group_temo .setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { // 點擊事件獲取的選擇對象 checkRadioButton = (RadioButton) group_temo .findViewById(checkedId); Toast.makeText(getApplicationContext(), "獲取的ID是" + checkRadioButton.getText(), Toast.LENGTH_LONG).show(); } }); } } 

布局檔案

 <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://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=".MainActivity" > <RadioGroup android:id="@+id/radioGroup1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" android:layout_alignParentTop="true" > <RadioButton android:id="@+id/radio0" android:layout_width="wrap_content" android:layout_height="wrap_content" android:checked="true" android:text="@string/text_java" /> <RadioButton android:id="@+id/radio1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/text_net" /> <RadioButton android:id="@+id/radio2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/text_php" /> </RadioGroup> </RelativeLayout> 

重點整理一下:透過 check() 方法可以預先設定預設選項,再用 getCheckedRadioButtonId() 取得目前被選中的 RadioButton;而 setOnCheckedChangeListener 則是監聽切換事件,一旦使用者點選某個選項,就能即時取得對應的內容。這個模式在做表單、設定頁時非常實用。

希望本文所述能對你的 Android 程式設計有所幫助。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved