RadioButton為單選按鈕,他需要與RadioGroup配合使用 對應的佈局代碼: Java代碼: 在上述代碼中,利用setCheckedChangeListener()監聽RadioGroup控制項狀態,獲取監聽結果輸出到TextView控制項里顯示 ...
RadioButton為單選按鈕,他需要與RadioGroup配合使用
對應的佈局代碼:
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 xmlns:app="http://schemas.android.com/apk/res-auto" 4 xmlns:tools="http://schemas.android.com/tools" 5 android:layout_width="match_parent" 6 android:layout_height="match_parent" 7 tools:context=".MainActivity" 8 android:orientation="vertical"> 9 10 <TextView 11 android:id="@+id/t1" 12 android:layout_width="match_parent" 13 android:layout_height="wrap_content" 14 android:gravity="center" 15 android:text="input" 16 android:textSize="25sp" /> 17 <RadioGroup 18 android:id="@+id/rg" 19 android:layout_width="wrap_content" 20 android:layout_height="wrap_content" 21 android:orientation="vertical"> 22 <RadioButton 23 android:id="@+id/rba" 24 android:layout_width="wrap_content" 25 android:layout_height="wrap_content" 26 android:text="A" 27 /> 28 <RadioButton 29 android:id="@+id/rbb" 30 android:layout_width="wrap_content" 31 android:layout_height="wrap_content" 32 android:text="B" 33 /> 34 <RadioButton 35 android:id="@+id/rbc" 36 android:layout_width="wrap_content" 37 android:layout_height="wrap_content" 38 android:text="C" 39 /> 40 <RadioButton 41 android:id="@+id/rbd" 42 android:layout_width="wrap_content" 43 android:layout_height="wrap_content" 44 android:text="D" 45 /> 46 </RadioGroup> 47 </LinearLayout>
Java代碼:
1 package com.example.administrator.myapplication; 2 3 import android.support.v7.app.AppCompatActivity; 4 import android.os.Bundle; 5 import android.view.View; 6 import android.widget.RadioButton; 7 import android.widget.RadioGroup; 8 import android.widget.TextView; 9 import android.widget.Toast; 10 11 public class MainActivity extends AppCompatActivity { 12 TextView t; 13 @Override 14 protected void onCreate(Bundle savedInstanceState) { 15 super.onCreate(savedInstanceState); 16 setContentView(R.layout.activity_main); 17 18 t=findViewById(R.id.t1); 19 RadioGroup rg = findViewById(R.id.rg); 20 rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { 21 @Override 22 public void onCheckedChanged(RadioGroup radioGroup, int checkdId) { 23 RadioButton rb = findViewById(checkdId); 24 String s = rb.getText().toString(); 25 t.setText("單擊了" +s); 26 } 27 }); 28 } 29 }
在上述代碼中,利用setCheckedChangeListener()監聽RadioGroup控制項狀態,獲取監聽結果輸出到TextView控制項里顯示