EventBus (一) 使用详解——初步使用EventBus
版权声明:本文为博主原创文章,未经博主允许不得转载。
前言:EventBus是上周项目中用到的,网上的文章大都一样,或者过时,有用的没几篇,经过琢磨,请教他人,也终于弄清楚点眉目,记录下来分享给大家。
相关文章:
1、《EventBus使用详解(一)——初步使用EventBus》
2、《EventBus使用详解(二)——EventBus使用进阶》
一、概述
EventBus是一款针对Android优化的发布/订阅事件总线。主要功能是替代Intent,Handler,BroadCast在Fragment,Activity,Service,线程之间传递消息.优点是开销小,代码更优雅。以及将发送者和接收者解耦。
1、下载EventBus的类库
源码:https://github.com/greenrobot/EventBus
2、基本使用
(1)自定义一个类,可以是空类,比如:
- public class AnyEventType {
- public AnyEventType(){}
- }
(2)在要接收消息的页面注册:
- eventBus.register(this);
(3)发送消息
- eventBus.post(new AnyEventType event);
(4)接受消息的页面实现(共有四个函数,各功能不同,这是其中之一,可以选择性的实现,这里先实现一个):
- public void onEvent(AnyEventType event) {}
(5)解除注册
- eventBus.unregister(this);
顺序就是这么个顺序,可真正让自己写,估计还是云里雾里的,下面举个例子来说明下。
首先,在EventBus中,获取实例的方法一般是采用EventBus.getInstance()来获取默认的EventBus实例,当然你也可以new一个又一个,个人感觉还是用默认的比较好,以防出错。
二、实战
先给大家看个例子:
当击btn_try按钮的时候,跳到第二个Activity,当点击第二个activity上面的First Event按钮的时候向第一个Activity发送消息,当第一个Activity收到消息后,一方面将消息Toast显示,一方面放入textView中显示。
按照下面的步骤,下面来建这个工程:
1、基本框架搭建
想必大家从一个Activity跳转到第二个Activity的程序应该都会写,这里先稍稍把两个Activity跳转的代码建起来。后面再添加EventBus相关的玩意。
MainActivity布局(activity_main.xml)
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical">
- <Button
- android:id="@+id/btn_try"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="btn_bty"/>
- <TextView
- android:id="@+id/tv"
- android:layout_width="wrap_content"
- android:layout_height="match_parent"/>
- </LinearLayout>
新建一个Activity,SecondActivity布局(activity_second.xml)
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical"
- tools:context="com.harvic.try_eventbus_1.SecondActivity" >
- <Button
- android:id="@+id/btn_first_event"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="First Event"/>
- </LinearLayout>
MainActivity.java (点击btn跳转到第二个Activity)
- public class MainActivity extends Activity {
- Button btn;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- btn = (Button) findViewById(R.id.btn_try);
- btn.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- // TODO Auto-generated method stub
- Intent intent = new Intent(getApplicationContext(),
- SecondActivity.class);
- startActivity(intent);
- }
- });
- }
- }
到这,基本框架就搭完了,下面开始按步骤使用EventBus了。
2、新建一个类FirstEvent
- package com.harvic.other;
- public class FirstEvent {
- private String mMsg;
- public FirstEvent(String msg) {
- // TODO Auto-generated constructor stub
- mMsg = msg;
- }
- public String getMsg(){
- return mMsg;
- }
- }
这个类很简单,构造时传进去一个字符串,然后可以通过getMsg()获取出来。
3、在要接收消息的页面注册EventBus:
在上面的GIF图片的演示中,大家也可以看到,我们是要在MainActivity中接收发过来的消息的,所以我们在MainActivity中注册消息。
通过我们会在OnCreate()函数中注册EventBus,在OnDestroy()函数中反注册。所以整体的注册与反注册的代码如下:
- package com.example.tryeventbus_simple;
- import com.harvic.other.FirstEvent;
- import de.greenrobot.event.EventBus;
- import android.app.Activity;
- import android.content.Intent;
- import android.os.Bundle;
- import android.util.Log;
- import android.view.View;
- import android.widget.Button;
- import android.widget.TextView;
- import android.widget.Toast;
- public class MainActivity extends Activity {
- Button btn;
- TextView tv;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- //注册EventBus
- EventBus.getDefault().register(this);
- btn = (Button) findViewById(R.id.btn_try);
- tv = (TextView)findViewById(R.id.tv);
- btn.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- // TODO Auto-generated method stub
- Intent intent = new Intent(getApplicationContext(),
- SecondActivity.class);
- startActivity(intent);
- }
- });
- }
- @Override
- protected void onDestroy(){
- super.onDestroy();
- EventBus.getDefault().unregister(this);//反注册EventBus
- }
- }
4、发送消息
发送消息是使用EventBus中的Post方法来实现发送的,发送过去的是我们新建的类的实例!
- EventBus.getDefault().post(new FirstEvent("FirstEvent btn clicked"));
完整的SecondActivity.java的代码如下:
- package com.example.tryeventbus_simple;
- import com.harvic.other.FirstEvent;
- import de.greenrobot.event.EventBus;
- import android.app.Activity;
- import android.os.Bundle;
- import android.view.View;
- import android.widget.Button;
- public class SecondActivity extends Activity {
- private Button btn_FirstEvent;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_second);
- btn_FirstEvent = (Button) findViewById(R.id.btn_first_event);
- btn_FirstEvent.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- // TODO Auto-generated method stub
- EventBus.getDefault().post(
- new FirstEvent("FirstEvent btn clicked"));
- }
- });
- }
- }
5、接收消息
接收消息时,我们使用EventBus中最常用的onEventMainThread()函数来接收消息,具体为什么用这个,我们下篇再讲,这里先给大家一个初步认识,要先能把EventBus用起来先。
在MainActivity中重写onEventMainThread(FirstEvent event),参数就是我们自己定义的类:
在收到Event实例后,我们将其中携带的消息取出,一方面Toast出去,一方面传到TextView中;
- public void onEventMainThread(FirstEvent event) {
- String msg = "onEventMainThread收到了消息:" + event.getMsg();
- Log.d("harvic", msg);
- tv.setText(msg);
- Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
- }
完整的MainActiviy代码如下:
- package com.example.tryeventbus_simple;
- import com.harvic.other.FirstEvent;
- import de.greenrobot.event.EventBus;
- import android.app.Activity;
- import android.content.Intent;
- import android.os.Bundle;
- import android.util.Log;
- import android.view.View;
- import android.widget.Button;
- import android.widget.TextView;
- import android.widget.Toast;
- public class MainActivity extends Activity {
- Button btn;
- TextView tv;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- EventBus.getDefault().register(this);
- btn = (Button) findViewById(R.id.btn_try);
- tv = (TextView)findViewById(R.id.tv);
- btn.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- // TODO Auto-generated method stub
- Intent intent = new Intent(getApplicationContext(),
- SecondActivity.class);
- startActivity(intent);
- }
- });
- }
- public void onEventMainThread(FirstEvent event) {
- String msg = "onEventMainThread收到了消息:" + event.getMsg();
- Log.d("harvic", msg);
- tv.setText(msg);
- Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
- }
- @Override
- protected void onDestroy(){
- super.onDestroy();
- EventBus.getDefault().unregister(this);
- }
- }
好了,到这,基本上算初步把EventBus用起来了,下篇再讲讲EventBus的几个函数,及各个函数间是如何识别当前如何调用哪个函数的。
如果我的文章有帮到你,请关注哦。
源码地址:http://download.csdn.net/detail/harvic880925/8111357
请大家尊重原创者版权,转载请标明出处:http://blog.csdn.net/harvic880925/article/details/40660137 谢谢!
EventBus (一) 使用详解——初步使用EventBus的更多相关文章
- EventBus (二) 使用详解——EventBus使用进阶
相关文章: 1.<EventBus使用详解(一)——初步使用EventBus> 2.<EventBus使用详解(二)——EventBus使用进阶> 一.概述 前一篇给大家装简单 ...
- EventBus的使用详解,功能为在Fragment,Activity,Service,线程之间传递消息
最近跟同事用到了EventBus的使用,之前不太了解EventBus,查阅资料发现EventBus还挺好用的,用法比较简单,下面就把我看到的关于EventBus的博客分享给大家,里面介绍了很多的使用详 ...
- EventBus使用详解(一)——初步使用EventBus
一.概述 EventBus是一款针对Android优化的发布/订阅事件总线.主要功能是替代Intent,Handler,BroadCast在Fragment,Activity,Service,线程之间 ...
- Android消息传递之EventBus 3.0使用详解
前言: 前面两篇不仅学习了子线程与UI主线程之间的通信方式,也学习了如何实现组件之间通信,基于前面的知识我们今天来分析一下EventBus是如何管理事件总线的,EventBus到底是不是最佳方案?学习 ...
- Android EventBus 3.0 实例使用详解
EventBus的使用和原理在网上有很多的博客了,其中泓洋大哥和启舰写的非常非常棒,我也是跟着他们的博客学会的EventBus,因为是第一次接触并使用EventBus,所以我写的更多是如何使用,源码解 ...
- 安卓高级EventBus使用详解
我本来想写但是在网上看了下感觉写得不如此作者写得好:http://www.jianshu.com/p/da9e193e8b03 前言:EventBus出来已经有一段时间了,github上面也有很多开源 ...
- EventBus详解
EventBus详解 简介 github原文 EventBus... * simplifies the communication between components - decouples eve ...
- EventBus使用详解(一)
一.概述 EventBus是一款针对Android优化的发布/订阅事件总线.主要功能是替代Intent,Handler,BroadCast在Fragment,Activity,Service,线程之间 ...
- 【Android】事件总线(解耦组件) EventBus 详解
当Android项目越来越庞大的时候,应用的各个部件之间的通信变得越来越复杂,例如:当某一条件发生时,应用中有几个部件对这个消息感兴趣,那么我们通常采用的就是观察者模式,使用观察者模式有一个弊病就是部 ...
随机推荐
- Base64的好处
1. 昨天的<MIME笔记>中提到,MIME主要使用两种编码转换方式----Quoted-printable和Base64----将8位的非英语字符转化为7位的ASCII字符. 虽然这样的 ...
- [笔记] 几个前端bug的解决方案
jQuery UI下被拖动的元素上飘 症状出现在几乎所有浏览器里.使用 1.10.x 的draggable,在滚动栏下移(即非处于页面顶部)的时候拖动draggable的元素,它会向上跳一段距离.解决 ...
- System.Net.Mail的应用,后端发送邮件
private void btn_send_Click(object sender, EventArgs e) { var emailAcount = ConfigurationManager.App ...
- 【LOJ】#2006. 「SCOI2015」小凸玩矩阵
题解 又是美好的一天,我今天的小目标是LOJ刷题数名次前进两名(虽然巨佬们都是BZOJ千题啊这样的><,我就在LOJ划划水吧,我永远喜欢LOJ 这道题要求K大值最小,又是什么什么大值最小, ...
- easyui layout 左右面板折叠后 显示标题
(function($){ var buttonDir = {north:'down',south:'up',east:'left',west:'right'}; $.extend($.fn.l ...
- HTML如何创建二级目录
#classify ul li div{width:100px; height:200px; display:none; position:absolute; left:100px; top ...
- 【WPF】ListView自定义分页
XAML: <Grid> <Grid.RowDefinitions> <RowDefinition Height="*"/> <RowDe ...
- [Gym - 100517K] Kingdom Division 2 二分
大致题意: 给出一个凸包,以及凸包内的两个点p1,p2,求有多少条经过凸包顶点的直线能够将凸包分割为两部分,且给出的两点分别属于不同的部分 枚举凸包的顶点,二分求出p1,p2线段左边的最大坐标L以及右 ...
- 去除win7桌面图标小箭头.bat
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Icons" ...
- HDU 6194【后缀数组】
题目链接[http://acm.hdu.edu.cn/showproblem.php?pid=6194] 题意: 给你一个长度不大于1e5的字符串,然后然你判断其子串严格出现k次的子串个数. 题解: ...