赞
踩
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() { //代码设置 radiobutton 是否选中 rb_1.setChecked(true); rb_2.setChecked(false); rb_3.setChecked(false); //获取选中状态 if (rb_1.isChecked()) { Log.d("rb_1", "true"); } } private void initClick() { //radio button 状态发生改变的监听事件 //Register a callback to be invoked when the checked radio button changes in this group //注册当选中的单选按钮在此组中更改时要调用的回调 rg_fruit.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { //group.getCheckedRadioButtonId() 获取选中后 radiobutton 按钮的id //checkedId 返回选中后 radioButton 按钮的id 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>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。