Android中单项选择效果的实现需要RadioGroup和RadioButton。选择按钮通过RadioButton实现,答案通过RadioGroup实现,在定义RadioGroup时已经将答案赋给了每个选项,在RadioGroup监听事件中做判断。
package com.helen;
import android.app.Activity;
import android.os.Bundle;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
public class StudyBook extends Activity {
/**
* 创建tv对象和radiogroup,radiobutton
*/
TextView tv;
RadioGroup rg;
RadioButton rb1;
RadioButton rb2;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main); // 设置布局
//获取对象
tv =(TextView)findViewById(R.id.tv);
rg = (RadioGroup)findViewById(R.id.rg);
rb1 = (RadioButton)findViewById(R.id.rb1);
rb2 = (RadioButton)findViewById(R.id.rb2);
//事件监听,判断答案是否正确
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
if(checkedId == rb1.getId())
{
display("your job is " + rb1.getText());
}
else
{
display("your job is " + rb2.getText());
}
}
});
}
/**
* 显示Toast提示信息
*
* @param str
*/
private void display(String str) {
Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView android:id="@+id/tv" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello"></TextView>
<RadioGroup android:id="@+id/rg" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:orientation="vertical"
>
<RadioButton android:id="@+id/rb1" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text = "@string/rb1"></RadioButton>
<RadioButton android:id="@+id/rb2" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text = "@string/rb2"></RadioButton>
</RadioGroup>
</LinearLayout>
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">what is your job?</string>
<string name="app_name">studyBook</string>
<string name="rb1">student</string>
<string name="rb2">engineer</string>
</resources>
效果如图: