Android开发之RadioButton和CheckBox

来源:互联网 发布:顾客关系管理数据 编辑:程序博客网 时间:2024/06/06 08:32

       如下图像是整体的布局

这是main.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    ><TextView      android:layout_width="fill_parent"     android:layout_height="wrap_content"     android:text="@string/hello"    /><RadioGroupandroid:id="@+id/gender"android:orientation="horizontal"android:layout_width="fill_parent"     android:layout_height="wrap_content"     >    <RadioButton    android:id="@+id/man"    android:layout_width="wrap_content"     android:layout_height="wrap_content"     android:text="@string/man"    />    <RadioButton    android:id="@+id/woman"    android:layout_width="wrap_content"     android:layout_height="wrap_content"     android:text="@string/woman"    /></RadioGroup><CheckBoxandroid:id="@+id/run"android:layout_width="fill_parent"     android:layout_height="wrap_content"     android:text="@string/run"/><CheckBoxandroid:id="@+id/sing"android:layout_width="fill_parent"     android:layout_height="wrap_content"     android:text="@string/sing"/><CheckBoxandroid:id="@+id/dance"android:layout_width="fill_parent"     android:layout_height="wrap_content"     android:text="@string/dance"/></LinearLayout>

这是RadioButton触发事件的核心代码

gender = (RadioGroup)findViewById(R.id.gender);        man = (RadioButton)findViewById(R.id.man);        woman = (RadioButton)findViewById(R.id.woman);        gender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {@Overridepublic void onCheckedChanged(RadioGroup group, int checkedId) {// TODO Auto-generated method stub    if(man.getId()==checkedId){    //System.out.println("男");    Toast.makeText(radioTest.this, "我是帅哥", Toast.LENGTH_LONG).show();    }else if(woman.getId()==checkedId){    //System.out.println("女");    Toast.makeText(radioTest.this, "我是美女", Toast.LENGTH_LONG).show();    }}});

这是CheckBox的触发事件的核心代码

run.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {@Overridepublic void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {// TODO Auto-generated method stubif(isChecked){//System.out.println("run checked");Toast.makeText(radioTest.this, "感觉很好!", Toast.LENGTH_LONG).show();}else{//System.out.println("run unchecked");Toast.makeText(radioTest.this, "坑爹啊!", Toast.LENGTH_LONG).show();}}});
从中我们可以看到单选按钮触发事件是绑定到了RadioGroup上面,而多选按钮是绑定到了每一个多选按钮上。

此外,我们看到还有Toast,这是一个提示消息,就像上面图像里的一样,用法很简单,就是一句话

Toast.makeText(radioTest.this, "我是美女", Toast.LENGTH_LONG).show();

我们依葫芦画瓢就可以了



原创粉丝点击