Androidstudio单选按钮
1.基本⽤法与事件处理:
1)RadioButton(单选按钮)
如题单选按钮,就是只能够选中⼀个,所以我们需要把RadioButton放到RadioGroup按钮组中,从⽽实现单选功能!先熟悉下如何使⽤RadioButton,⼀个简单的性别选择的例⼦:另外我们可以为外层RadioGroup设置orientation属性然后设置RadioButton 的排列⽅式,是竖直还是⽔平~
效果图:
PS:笔者的⼿机是Android 5.0.1的,这⾥的RadioButton相⽐起旧版本的RadioButton,稍微好看⼀点~
布局代码如下:
<LinearLayout xmlns:android="schemas.android/apk/res/android"
xmlns:tools="schemas.android/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="请选择性别"
android:textSize="23dp"
/>
<RadioGroup
android:id="@+id/radioGroup"
android:layout_width="wrap_content"
htmlradio设置默认的按钮android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioButton
android:id="@+id/btnMan"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="男"
android:checked="true"/>
<RadioButton
android:id="@+id/btnWoman"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="⼥"/>
</RadioGroup>
<Button
android:id="@+id/btnpost"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="提交"/>
</LinearLayout>
获得选中的值:
这⾥有两种⽅法,
第⼀种是为RadioButton设置⼀个事件setOnCheckChangeListener
例⼦代码如下:
RadioGroup radgroup = (RadioGroup) findViewById(R.id.radioGroup);
//第⼀种获得单选按钮值的⽅法
//为radioGroup设置⼀个:setOnCheckedChanged()
radgroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton radbtn = (RadioButton) findViewById(checkedId);
Toast.makeText(getApplicationContext(), "按钮组值发⽣改变,你选了" + Text(), Toast.LENGTH_LONG).show();
}
});
运⾏效果图:
PS:另外有⼀点要切记,要为每个RadioButton添加⼀个id,不然单选功能会⽣效
第⼆种⽅法是通过单击其他按钮获取选中单选按钮的值,当然我们也可以直接获取,这个看需求~
例⼦代码如下:
Button btnchange = (Button) findViewById(R.id.btnpost);
RadioGroup radgroup = (RadioGroup) findViewById(R.id.radioGroup);
//为radioGroup设置⼀个:setOnCheckedChanged()
btnchange.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
for (int i = 0; i < ChildCount(); i++) {
RadioButton rd = (RadioButton) ChildAt(i);
if (rd.isChecked()) {
Toast.makeText(getApplicationContext(), "点击提交按钮,获取你选择的是:" + rd.getText(), Toast.LENGTH_LONG).show();
break;
}
}
}
});
运⾏效果图:
代码解析:这⾥我们为提交按钮设置了⼀个setOnClickListener事件,每次点击的话遍历⼀次RadioGroup判断哪个按钮被选中我们可以通过下述⽅法获得RadioButton的相关信息!
getChildCount( )获得按钮组中的单选按钮的数⽬;
getChinldAt(i):根据索引值获取我们的单选按钮
isChecked( ):判断按钮是否选中

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。