最近开始学习安卓一些基本的编程,于是开始总结、整理各个要点,便于记住以及回顾。
RadioButton是最普通的UI组件之一,继承了Button类,可以直接使用Button支持的各种属性和方法。
RadioButton与普通按钮不同的是,它多了一个可以选中的功能,可额外指定一个android:checked属性,该属性可以指定初始状态时是否被选中,其实也可以不用指定,默认初始状态都不选中。
使用RadioButton必须和单选框RadioGroup一起使用,在RadioGroup中放置RadioButton,通过setOnCheckedChangeListener( )来响应按钮的事件;
下面是一个实例:
layout文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.testapp.MainActivity" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/information"
/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/sex"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/sex"/>
<RadioGroup
android:id="@+id/rgroup"
android:orientation="horizontal"
android:layout_height="wrap_content"
android:layout_width="match_parent"
>
<RadioButton
android:id="@+id/ch1"
android:text="@string/male"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:checked="true"
/>
<RadioButton
android:id="@+id/ch2"
android:text="@string/female"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:checked="true"
/>
</RadioGroup>
</LinearLayout>
<TextView
android:id="@+id/show"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/hint"
/>
</LinearLayout>
这里RadioButton的android:checked属性可以多个都选择为true,但运行之后只会选择最后一个checked属性作为初始状态。
很多初学者都会遇到一个问题:程序代码(包括xml文件)均无错误提示,但是在设备上运行时候却出错,其中一个原因就是布局或者组件没有指定layout_width和layout_height属性,导致运行出错!
Java代码:
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
private RadioGroup rgroup;
private TextView show;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rgroup=(RadioGroup)findViewById(R.id.rgroup);
show=(TextView)findViewById(R.id.show);
//通过setOnCheckedChangeListener( )来响应按钮的事
rgroup.setOnCheckedChangeListener(new OnCheckedChangeListener(){
@Override
public void onCheckedChanged(RadioGroup rg,int checkedId)
{
switch(checkedId){
case R.id.ch1:show.setText("您的性别为:男性");break;
case R.id.ch2:show.setText("您的性别为:女性");break;
}
}
});
}
}