android单选按钮事件

前段时间忙着找工作,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文档。晚上的话再接着来个长按事件和下拉列表框的使用。


  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值