Android RadioButton使用
例题2-12
activity_main.xml代码
1 <?xml version="1.0" encoding="utf-8"?> 2 <GridLayout android:layout_width="fill_parent" 3 android:layout_height="fill_parent" 4 android:columnCount="4" 5 android:rowCount="6" 6 xmlns:android="http://schemas.android.com/apk/res/android"> 7 <RadioGroup> 8 <RadioButton android:id="@+id/boy" 9 android:layout_width="wrap_content" 10 android:layout_height="wrap_content" 11 android:checked="true" 12 android:text="男"/> 13 <RadioButton android:id="@+id/girl" 14 android:layout_width="wrap_content" 15 android:layout_height="wrap_content" 16 android:text="女"/> 17 </RadioGroup> 18 <Button android:id="@+id/but1" 19 android:layout_width="wrap_content" 20 android:layout_height="wrap_content" 21 android:text="确认" 22 android:layout_columnSpan="4"/> 23 <TextView android:id="@+id/text1" 24 android:layout_height="wrap_content" 25 android:layout_width="wrap_content" 26 android:text="" /> 27 </GridLayout>
mainactivity.java代码
1 package com.example.hello; 2 3 import androidx.appcompat.app.AppCompatActivity; 4 5 import android.os.Bundle; 6 import android.telephony.SmsManager; 7 import android.view.View; 8 import android.widget.Button; 9 import android.widget.CheckBox; 10 import android.widget.ProgressBar; 11 import android.widget.RadioButton; 12 import android.widget.TextView; 13 14 public class MainActivity extends AppCompatActivity { 15 Button but1; 16 TextView textView; 17 RadioButton radioButton1,radioButton2; 18 @Override 19 protected void onCreate(Bundle savedInstanceState) { 20 super.onCreate(savedInstanceState); 21 setContentView(R.layout.activity_main); 22 textView = (TextView)findViewById(R.id.text1); 23 but1 = (Button)findViewById(R.id.but1); 24 radioButton1 = (RadioButton)findViewById(R.id.boy); 25 radioButton2 = (RadioButton)findViewById(R.id.girl); 26 but1.setOnClickListener(new View.OnClickListener() { 27 @Override 28 public void onClick(View v) { 29 String s=""; 30 if(radioButton1.isChecked()) 31 s=s+radioButton1.getText(); 32 if (radioButton2.isChecked()) 33 s=s+radioButton2.getText(); 34 textView.setText("性别:"+s); 35 } 36 }); 37 38 } 39 40 }