当前位置:操作系统 > 安卓/Android >>

ndroid基础控件

这两个控件就是提供给用户进行选择的时候一种好的体验:比如有时候不需要用户亲自输入,那么我们就提供给用户操作更快捷的选项。单选按钮(RadioButton)就是在这个选项中,用户只能选择一个选项。而复选框(CheckBox)控件顾名思义就是可以选择多个选项。下面就介绍这两个控件。
 
5.2.1示例:
 
示例一:RadioButton控件的用法(这里采用布局文件方法来演示,先说明RadioButton的用法):
 
<?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" >
 
<!--这里是定义了一组RadioButton,然后分为三个选项-->
 
    <RadioButton
 
        android:id="@+id/first_radiobutton"
 
        android:checked="true"
 
        android:layout_width="fill_parent"
 
        android:layout_height="wrap_content"
 
        android:onClick="onAction"
 
        android:text="男" />
 
 
 
    <RadioButton
 
        android:id="@+id/second_radiobutton"
 
        android:layout_width="fill_parent"
 
        android:layout_height="wrap_content"
 
        android:onClick="onAction"
 
        android:text="女" />
 
 
 
    <RadioButton
 
        android:id="@+id/third_radiobutton"
 
        android:layout_width="fill_parent"
 
        android:layout_height="wrap_content"
 
        android:onClick="onAction"
 
        android:text="其他" />
 
 
 
</LinearLayout>
 
这上面是给出的布局文件的代码,这里主要是实现图5.1的布局界面,而真正要实现功能的代码不在这块。上述代码中的:android:checked="true"; 是用来设置默认选中的那个选项,而android:onClick="onAction"是设置监听事件方法,在java代码中实现。这里可以使用RadioGroup要定义一组按钮,也就是说,在这一个组内,选项有用。这里采用java代码实现。代码如下:
 
package xbb.bzq.android.app;
 
 
 
import android.app.Activity;
 
import android.os.Bundle;
 
import android.view.View;
 
import android.widget.RadioButton;
 
 
 
public class RadioButtonAndCheckBoxTestActivity extends Activity {
 
//定义三个RadioButton变量
 
private RadioButton mButton1, mButton2, mButton3;
 
 
 
@Override
 
public void onCreate(Bundle savedInstanceState) {
 
super.onCreate(savedInstanceState);
 
setContentView(R.layout.main);
 
//实例化三个单选按钮控件
 
mButton1 =
 
 (RadioButton) findViewById(R.id.first_radiobutton);
 
mButton2 =
 
 (RadioButton) findViewById(R.id.second_radiobutton);
 
mButton3 =
 
 (RadioButton) findViewById(R.id.third_radiobutton);
 
}
 
 
 
   /**
 
    * 这是实现的监听方法,主要是实现修改选项的值
 
    * @param v
 
    */
 
public void onAction(View v) {
 
//通过获取id来判断用户的选择,然后改变控件的选择状态
 
switch (v.getId()) {
 
case R.id.first_radiobutton:
 
mButton2.setChecked(false);
 
mButton3.setChecked(false);
 
mButton1.setChecked(true);
 
break;
 
case R.id.second_radiobutton:
 
mButton1.setChecked(false);
 
mButton3.setChecked(false);
 
mButton2.setChecked(true);
 
break;
 
 
 
case R.id.third_radiobutton:
 
mButton2.setChecked(false);
 
mButton1.setChecked(false);
 
mButton3.setChecked(true);
 
break;
 
}
 
}
 
}
补充:移动开发 , Android ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,