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>


效果如图:

更多相关文章

  1. 转 Android监听键盘弹出收起
  2. 实现对特定内容改变字体颜色的TextView
  3. Android启动画面实现
  4. Android基于ViewFilpper实现文字LED显示效果示例
  5. Android的MediaRecorder架构介绍
  6. Android(安卓)通过代码实现控制数据网络的开关(仅适用于5.0以上)
  7. Android实现微信分享及注意事项
  8. Android实现列表单选和多选,ListView+CheckedTextView
  9. 浅谈Java中Collections.sort对List排序的两种方法

随机推荐

  1. 在Android中使用Lua脚本 —— Programing
  2. android中的weight
  3. Android之系统给我们提供的常见的Activit
  4. android 使用eclipse编译 FBReaderJ流程
  5. Android日记之2012/02/16——浅谈Android
  6. Android里的媒体库
  7. 关于安装Android(安卓)Studio的一些问题
  8. android开发问题解决日志
  9. Android(安卓)TextView内容过长加省略号,
  10. 演化理解 Android(安卓)异步加载图片