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

来源:互联网 发布:数据库应用程序开发 编辑:程序博客网 时间:2024/05/16 04:48

页面之间的传值,有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消失"));//发送消息 

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

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

二、示例代码
源码下载

0 0
原创粉丝点击