今天学习了单选按钮的简单应用:先来看看成果吧!
今天不想说太多,直接上源码吧:
public class MainActivity extends AppCompatActivity {
RadioGroup rg;
Button bt;
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_main);
bt = (Button) findViewById (R.id.bt); //获取“验证按钮”
rg = (RadioGroup) findViewById (R.id.rg); // 获取布局中单选按钮
bt.setOnClickListener (new View.OnClickListener () { //为”验证“按钮设置监听器
@Override
public void onClick (View v) {
for (int i = 0; i < rg.getChildCount (); i++) {
RadioButton radioButton = (RadioButton) rg.getChildAt (i);
if (radioButton.isChecked ()) { //判断按钮是否选中
if (radioButton.getText ().equals ("B:100")) { // 判断答案时候正确
Toast.makeText (MainActivity.this, "回答正确", Toast.LENGTH_SHORT).show ();
}else {
AlertDialog.Builder builder = new AlertDialog.Builder (MainActivity.this);
builder.setMessage ("回答错误,下面请看解析:当张山换完零钱之后," +
"给了顾客75还有价值25元的商品,自己还剩下了25元。这时," +
"李石来找张山要钱,张山把自己剩下的相当于是李石的25元给了李石," +
"另外自己掏了75元。这样张山赔了一个25元的商品和75元的人民币," +
"总共价值100元。");
builder.setPositiveButton ("确定", null).show (); // 单机确定消失
}
break;
}
}
}
});
}
}
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="一天,张山的店里来了一个顾客,挑了25元的货,顾客拿出100元,张山没有零钱找不开,就到隔壁李石的店里把这100元换成零钱,回来给顾客找了75元零钱。
过一会,李石来找张山,说刚才的那100是假钱,张山马上给李石换了张真钱,
问张山赔了多少钱?"
/>
<!--使用RadioGroup与RadioButton组成单选按钮组-->
<RadioGroup
android:id="@+id/rg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingStart="10dp"
android:paddingTop="30dp">
<RadioButton
android:id="@+id/rb_a"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="A:80"/>
<RadioButton
android:id="@+id/rb_b"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="B:100"/>
<RadioButton
android:id="@+id/rb_c"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="C:110"/>
<RadioButton
android:id="@+id/rb_d"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="D:150"/>
<Button
android:id="@+id/bt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="验证 "/>
</RadioGroup>