RadioButton练习(android)
16lz
2021-01-24
Radio 单选是由 RadioGroup 与 RadioButton 组成的,这个很简单,看代码就会了
main.xml
<? xmlversion="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" >
< TextView
android:layout_width ="fill_parent"
android:layout_height ="wrap_content"
android:text ="你的性别:请选择答案" />
< RadioGroup
android:id ="@+id/rg1"
android:layout_width ="wrap_content"
android:layout_height ="wrap_content"
android:orientation ="vertical"
android:layout_x ="3px"
android:layout_y ="54px"
>
< RadioButton
android:id ="@+id/rb1"
android:layout_width ="wrap_content"
android:layout_height ="wrap_content"
android:text ="男生"
/>
< RadioButton
android:id ="@+id/rb2"
android:layout_width ="wrap_content"
android:layout_height ="wrap_content"
android:text ="女生"
/>
</ RadioGroup >
< Button
android:id ="@+id/btn"
android:layout_width ="wrap_content"
android:layout_height ="wrap_content"
android:text ="测试"
/>
</ LinearLayout >
代码
packagezziss.android.radiotest;importandroid.app.Activity;
importandroid.os.Bundle;
importandroid.view.View;
importandroid.widget.Button;
importandroid.widget.RadioButton;
importandroid.widget.RadioGroup;
importandroid.widget.Toast;
public classRadioTestActivity extendsActivity{
/** Calledwhentheactivityisfirstcreated. */
RadioGrouprg1;
RadioButtonrb1;
RadioButtonrb2;
Buttonibtn;
@Override
public voidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
rg1=(RadioGroup) this.findViewById(R.id.rg1);
rb1=(RadioButton) this.findViewById(R.id.rb1);
rb2=(RadioButton) this.findViewById(R.id.rb2);
rg1.setOnCheckedChangeListener( newRadioGroup.OnCheckedChangeListener(){
@Override
public voidonCheckedChanged(RadioGroupgroup, intcheckedId){
// TODOAuto-generatedmethodstub
if(checkedId==rb1.getId())
{
ShowInfo(rb1.getText().toString());
}
if(checkedId==rb2.getId())
{
ShowInfo(rb2.getText().toString());
}
}
});
ibtn=(Button) this.findViewById(R.id.btn);
ibtn.setOnClickListener( newView.OnClickListener(){
@Override
public voidonClick(Viewv){
// TODOAuto-generatedmethodstub
intid=rg1.getCheckedRadioButtonId();
if(id!=-1)
showIdText(id);
else
ShowInfo("请选择");
}
});
}
private voidShowInfo(Stringstr)
{
Toasttoast=Toast.makeText( this,str,Toast.LENGTH_SHORT);
toast.show();
}
private voidshowIdText( intaId)
{
ShowInfo(((RadioButton) this.findViewById(aId)).getText().toString());
}
}
更多相关文章
- unity Android(安卓)csv 数据持久化
- android 反编译,反,注射LOG
- 提示Android(安卓)requires compiler compliance level 5.0 or 6
- 自定义 listivew (android)
- Android(安卓)滑动返回Activity的实现代码
- 最简单的BufferQueue测试程序(一)
- Android(安卓)cocos2d 弹弓游戏 Catapult 源代码 完成
- Android之RecyclerView实现时光轴
- Android(安卓)使用JAVA代码控制UI界面