EventBus小实例-传值、控制其他页控件显示

页面之间的传值,有android基础的童鞋都会知道,可以通过Intent进行传值,但是动态控制另一个页面控件的显示恐怕这个就不好用了吧,下面我们介绍一个比较好用的框架-EventBus,通过实例介绍它的使用(要引入jar包才能使用EventBus,jar包在源码下载中)。
一、介绍一下EventBus
使用EventBus的步骤:
1.新建一个类:作为消息类

package com.example.eventbus;

/**
 * @author 王飞
 * @since 2015年8月1日
 * 
 */
public class TestEvent {
    private String mMsg;

    public TestEvent(String mMsg) {
        this.mMsg = mMsg;
    }

    public String getMsg() {
        return mMsg;
    }
}

2.在onCreate()方法出注册:

EventBus.getDefault().register(this);// 注册EventBus  


//注册:三个参数分别是,消息订阅者(接收者),接收方法名,事件类 
EventBus.getDefault().register(this,"setTextA",SetTextAEvent.class);  
EventBus.getDefault().register(this,"setTextB",SetTextBEvent.class);  
EventBus.getDefault().register(this,"messageFromSecondActivity",SecondActivityEvent.class);  
EventBus.getDefault().registerSticky(this, "messageFromSecondActivity", SecondActivityEvent.class);
EventBus.getDefault().register(this,"countDown",CountDownEvent.class);  

3.创建方法接收传值:

public void onEventMainThread(TestEvent testEvent){  
        String mString="收到消息"+testEvent.getMsg();  
        mTextView.setText(mString);  
        mButton2.setVisibility(View.GONE);  

    }

4.在onDestory()中取消注册:

@Override  
    protected void onDestroy() {  
        super.onDestroy();  
        EventBus.getDefault().unregister(this);//取消注释  
    }  

5.发送消息

EventBus.getDefault().post(new TestEvent("button2消失"));//发送消息 

顺序不分先后,不要忘记就好了。

看后是不是有点类似于广播哦

二、示例代码
源码下载

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值