1. 程式人生 > >android 之RadioButton單選控制元件

android 之RadioButton單選控制元件


示例程式碼:

前端程式碼:

<?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"
  >
    <RadioGroup
        android:id="@+id/radioButton_gender"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        >
        <RadioButton
            android:layout_gravity="center_horizontal"
            android:text="女"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/radioButton_female"
            />
        <RadioButton
            android:layout_gravity="center_horizontal"
            android:text="男"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/radioButton_male"
            />
    </RadioGroup>
</LinearLayout>

業務邏輯:

package com.example.tf.radiobutton;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener {
    //1.尋找控制元件
    private RadioGroup radioGroup_gender;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    //2.尋找控制元件
    this.radioGroup_gender = (RadioGroup) this.findViewById(R.id.radioButton_gender);
    //註冊一個監聽事件
    this.radioGroup_gender.setOnCheckedChangeListener(this);
    }
    /**
     * 當單選按鈕的狀態發生變化時自動呼叫的方法
     * @param radioGroup 單選按鈕所在的按鈕組的物件
     * @param checkedId  使用者選中的單選按鈕的id值
     */
    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
        //得到使用者選中的  RadioButton物件
         RadioButton radioButton_checked = (RadioButton) radioGroup.findViewById(checkedId);
        //將得到的內容轉化成字串形式
         String gender = radioButton_checked.getText().toString();

         Toast.makeText(this, gender, Toast.LENGTH_SHORT).show();

        switch (checkedId){
            case R.id.radioButton_male:
                //當用戶點選男性按鈕時執行的程式碼
                System.out.println("男性");
                break;
            case R.id.radioButton_female:
                //當用戶點選女性按鈕時執行的程式碼
                System.out.println("女性");
                break;
        }
    }
}