public class MainActivity extends AppCompatActivity {
private RadioGroup rg_fruit;
private RadioButton rb_1, rb_2, rb_3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initData();
initClick();
}
private void initView() {
rg_fruit = findViewById(R.id.rg_fruit);
rb_1 = findViewById(R.id.radioButton);
rb_2 = findViewById(R.id.radioButton2);
rb_3 = findViewById(R.id.radioButton3);
}
private void initData() {
rb_1.setChecked(true);
rb_2.setChecked(false);
rb_3.setChecked(false);
if (rb_1.isChecked()) {
Log.d("rb_1", "true");
}
}
private void initClick() {
rg_fruit.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.radioButton:
Toast.makeText(MainActivity.this, "梨", Toast.LENGTH_SHORT).show();
break;
case R.id.radioButton2:
Toast.makeText(MainActivity.this, "香蕉", Toast.LENGTH_SHORT).show();
break;
case R.id.radioButton3:
Toast.makeText(MainActivity.this, "柿子", Toast.LENGTH_SHORT).show();
break;
default:
throw new IllegalStateException("Unexpected value: " + checkedId);
}
}
});
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="兄弟几个真和气,天天并肩坐一起,少时喜欢绿衣服,老来都穿黄色衣。(猜一水果)"
android:textColor="@color/black"
android:textSize="30sp" />
<RadioGroup
android:id="@+id/rg_fruit"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RadioButton
android:layout_marginTop="30dp"
android:id="@+id/radioButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="梨"
android:checked="true"
android:textSize="30sp" />
<RadioButton
android:layout_marginTop="30dp"
android:id="@+id/radioButton2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="香蕉"
android:textSize="30sp" />
<RadioButton
android:layout_marginTop="30dp"
android:id="@+id/radioButton3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="柿子"
android:textSize="30sp" />
</RadioGroup>
</LinearLayout>