4.单选按钮
MainActivity.java:
package com.example.phone2;
import android.os.Bundle;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RadioButton;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
RadioButton rb1, rb2, rb3;
RadioGroup rg;
TextView tvResult;
@Override
protected void onCreate(BundlesavedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvResult = (TextView)findViewById(R.id.tv_result);
rb1 = (RadioButton) findViewById(R.id.rbt_classical);//通过ID找到CheckBox
rb2 = (RadioButton)findViewById(R.id.rbt_novel);
rb3 = (RadioButton)findViewById(R.id.rbt_essays);
rg = (RadioGroup)findViewById(R.id.favor);
//rg.check(R.id.rbt_essays); //效果相同
rb3.setChecked(true); //设置“散文随笔”为选中状态
tvResult.setText("\n您感兴趣的图书:" + rb3.getText().toString());
rg.setOnCheckedChangeListener(cBoxListener);//对CheckBox进行监听
}
private OnCheckedChangeListenercBoxListener = new OnCheckedChangeListener() {
@Override
public voidonCheckedChanged(RadioGroup group, int checkedId) {
if (R.id.rbt_classical ==checkedId) {
tvResult.setText("\n您感兴趣的图书:" +rb1.getText().toString());
setTitle(String.valueOf(rb1.getText()));
} else if (R.id.rbt_novel ==checkedId) {
tvResult.setText("\n您感兴趣的图书:" + rb2.getText().toString());
setTitle(String.valueOf(rb2.getText()));
} else if (R.id.rbt_essays== checkedId) {
tvResult.setText("\n您感兴趣的图书:" + rb3.getText().toString());
}
}
};
}
activity_main.xml:
<?xml version="1.0"encoding="utf-8"?>
<LinearLayout xmlns:android="网址/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp"
android:paddingTop="10dp"
>
<TextView
android:id="@+id/favourite_label"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:text="请选择一个您感兴趣的图书类别" />
<RadioGroup
android:id="@+id/favor"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<RadioButton
android:id="@+id/rbt_classical"
android:checked="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="古典文学" />
<!--设置android:checked 属性值为"true",将该选项设置为选中状态-->
<RadioButton
android:id="@+id/rbt_novel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="当代小说" />
<RadioButton
android:id="@+id/rbt_essays"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="散文随笔" />
</RadioGroup>
<TextView
android:id="@+id/tv_result"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#0000ff"
android:textSize="17sp"
android:text="\n您感兴趣的图书:古典文学" />
</LinearLayout>