EventBus 基础篇
来源:互联网 发布:韩国社交软件sns 编辑:程序博客网 时间:2024/06/06 03:07
最近在研究RxJava ,突然想起了事件分发另一个强大的框架Eventbus ,并且项目经常用到,特意整理了下。
what is Eventbus?
官方的解释为:
EventBus is a publish/subscribe event bus optimized for Android.
它是专门为优化安卓一个 发布者/订阅者的事件总线。
发布者,发布事件。通过事件总线(其实就是在一个单例内部维持着一个map对象存储了一堆的方法),分发给订阅者。
它的优点:
轻量、简单、降低耦合。
用法:
1.声明Event事件
public class MessageEvent { /* Additional fields if needed */ }
2.注册
eventBus.register(this);
声明方法,有四种方法,最主要的是:
@Subscribe public void onEventMainThread(CommonEvent event) { }
3.发布事件
eventBus.post(event);
例子:
在oncrete() 方法中注册,无论是Activity 还是Fragment ,不在这里注册会报错。
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); EventBus.getDefault().register(this); btn=(Button)findViewById(R.id.btn); tv=(TextView)findViewById(R.id.tv); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent=new Intent(MainActivity.this,SecondActivity.class); startActivity(intent); } }); }
在OnDestroy中反注册
@Override protected void onDestroy() { super.onDestroy(); EventBus.getDefault().unregister(this); }
声明订阅者:
@Subscribe public void onEventMainThread(CommonEvent event) { if(event.getType().equals(CommonEvent.TYPE_99)){ tv.setText("从第二个页面来的:eventtype="+event.getType()); } }
在需要触发事件的位置提交事件:例如我在第二个界面提交事件,在第一个页面接受:
EventBus.getDefault().post(new CommonEvent(CommonEvent.TYPE_99));
代码并不难,希望通过我这个例子,一是巩固自己的学习和理解,二是希望更多的人更好的学习,我会再接再厉,写更多的博文。
源码下载
我的微信公众号:行走的那些事,欢迎大家扫一扫。
0 0
- EventBus 基础篇
- EventBus基础
- Android学习之EventBus基础篇
- EventBus使用之基础
- EventBus使用之基础
- android EventBus基础介绍
- EventBus---基础讲解
- EventBus 3.0 (一) 基础
- EventBus 3.0使用基础
- EventBus使用之基础
- EventBus使用基础
- EventBus之基础使用详解
- EventBus篇一:ThreadMode
- EventBus
- EventBus
- EventBus
- EventBus
- EventBus
- 转:那些年我们一起清除过的浮动
- 【android NDK JNI】android-ndk-r9d+adt-bundle-windows环境搭建-Hello-jni案例说明
- MySQL 加锁处理分析
- 倒计时(获取验证码的倒计时)
- 60个国外免费3D模型下载网站
- EventBus 基础篇
- 外挂制作必备工具下载.
- RESTful设计原则和样例(开发前后台接口)
- delete未提交rollback是否会改变行号
- 基于RESTful API 怎么设计用户权限控制?
- 后台启动Activity
- java端RESTful web services的几种实现方式
- linux gzip gunzip
- Android View 事件分发机制 源码解析