RadioGroup、RadioButton:
下面看一下我们今天写的例子:
radio_layout.xml文件内容:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Radio Demo" />
<RadioGroup
android:id="@+id/sexRg"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:checkedButton="@+id/female"
>
<RadioButton
android:id="@+id/female"
android:text="女"/>
<RadioButton
android:id="@+id/male"
android:text="男"/>
</RadioGroup>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="addRadioButton"
android:id="@+id/appendRadio"/>
</LinearLayout>
</ScrollView>
</LinearLayout>
Activity中的代码:
package cn.calss3g.activity;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
public class UITest3Activity extends Activity
implements OnCheckedChangeListener{
RadioGroup rg = null;
Button addBtn;
private static final String TAG = "TAG";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.radio_layout);
findViews();
//指定某个选项被选中
rg.check(R.id.male);
//获取当前选项组中被选中的选项的id
int checkedId = rg.getCheckedRadioButtonId();
RadioButton rb = (RadioButton) this.findViewById(checkedId);
Log.i(TAG,rb.getText().toString());
}
private void findViews(){
rg = (RadioGroup) this.findViewById(R.id.sexRg);
//注册监听器
rg.setOnCheckedChangeListener(this);
addBtn = (Button) this.findViewById(R.id.appendRadio);
addBtn.setOnClickListener(new OnClickListener(){
public void onClick(View v){
//动态增加RadioButton
RadioButton newRb = new RadioButton(UITest3Activity.this);
newRb.append("不明");
newRb.setId(100);
//添加到RadioGroup中
rg.addView(newRb);
}
});
}
//覆盖OnCheckedChangeListener接口的抽象方法
public void onCheckedChanged(RadioGroup group, int checkedId) {
if(group.getId()==R.id.sexRg){
RadioButton rb = (RadioButton) this.findViewById(checkedId);
Log.i(TAG,rb.getText().toString());
}
}
}
看看效果吧:
点击addRadioButton在看效果: