前段时间忙着找工作,android也是放了好久没去碰了,突然有些怀念了就拿起了书看了一下单选按钮组件。说实话android的组件是挺多的有的组件使用起来也比较麻烦还要结合adapter来使用,今天就来点简单的吧。搞一下单选按钮的选中事件就行了。
1.单选按钮标签为RadioGroup,这个当然是单选按钮的父节点了那子节点就是RadioButton了,先上一个自己写的单选按钮界面
界面的话就一段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"
/>
<RadioGroup
android:id="@+id/group"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:checkedButton="@+id/hainan"
android:textSize="20px"
>
<RadioButton
android:text="海南"
android:id="@+id/hainan"
/>
<RadioButton
android:text="上海"
android:id="@+id/shanghai"
/>
</RadioGroup>
</LinearLayout>
这里要注意的就是Radio要写在RadioGroup里不然程序就运行不起来了
2.选中事件OnCheckedChangeListener,这个东西不要写错了View里面是没有这个事件的,每个RadioButton都有一个Id与之相对应。下面就来看下怎么用了
package org.lxh.checkbox;
import android.app.Activity;
import android.os.Bundle;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class CheckboxActivity extends Activity {
private RadioGroup group;
private RadioButton hainan;
private RadioButton shanghai;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
group=(RadioGroup)this.findViewById(R.id.group);
hainan=(RadioButton)this.findViewById(R.id.hainan);
shanghai=(RadioButton)this.findViewById(R.id.shanghai);
group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
//如果‘海南’这个单选按钮被选中了
if(hainan.getId()==checkedId){
//弹出吐司通知
Toast.makeText(CheckboxActivity.this, hainan.getText().toString(), Toast.LENGTH_LONG).show();
}else{
Toast.makeText(CheckboxActivity.this, shanghai.getText().toString(), Toast.LENGTH_LONG).show();
}
}
});
}
}
很简单吧只要把事件名称记住了就都好说,记不得就看看API文档。晚上的话再接着来个长按事件和下拉列表框的使用。