学习笔记-Android单项选择效果实现

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>


效果如图:
[img]http://dl.iteye.com/upload/attachment/442605/009f5554-654d-3e7d-98d6-efd9166ee9ba.png[/img]
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值