EventBus---使用
来源:互联网 发布:用手机听小说的软件 编辑:程序博客网 时间:2024/05/02 01:44
EventBus是一个简单的事件订阅和分发的总线机制,主要的目的是简化Android BroadCast对事件的分发。在本篇博客中,主要目的是学会使用EventBus,接下来我会分两次详解EventBus事件注册和事件分发。EventBus下载地址https://github.com/greenrobot/EventBus
1、下载EventBus,我是以zip格式下载的,下载后解压将EventBus
的Android工程导入Eclipse座位libiary工程
2、新建工程EventBusDemo,将EventBus座位自己的library工程
如下图
3、新建一个Activity DemoActivity。此时源码的目录结构如下
4、EventBus分事件注册和事件分发两个部分,我们打算在MainActivity中注册一个事件,然后在DemoActivity中分发事件,MainActivity收到DemoActivity分发的事件后做出自定义的处理,以上就是这个示例工程的思路。
4、1 MainActivity中注册事件
EventBus注册很简单,就一句话:
EventBus.getDefault().register(this);
注册完成后需要写自己的事件处理,这里为了简单,只写了
onEventMainThread,参数为String类型,收到事件后只是简单的将字符串Log一下,所以MainActivity代码如下:
public class MainActivity extends Activity { private String TAG = "MainActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); EventBus.getDefault().register(this); startActivity(new Intent(this,DemoActivity.class)); } public void onEventMainThread(String event) { Log.i(TAG,event);; } @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); EventBus.getDefault().unregister(this); }}
在注册完成后我就直接到了DemoActivity,准备在DemoActivity中分发事件
4、2 DemoActivity中分发事件
DemoActivity中只有一个TextView,点击TextView就分发一次事件。
DemoActivity的布局
<RelativeLayout 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" tools:context="com.example.eventbusdemo.DemoActivity" > <Button android:layout_centerInParent="true" android:id="@+id/send" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="EventBus" /></RelativeLayout>
DemoActivity源代码
public class DemoActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_demo); findViewById(R.id.send).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub EventBus.getDefault().post("demo"); } }); }}
5、运行结果
启动应用后,应用进入DemoActivity中,点击TextView分发事件,MainActivity收到分发的事件后,将字符串Log一下。
运行结果如下
以上写的只是EventBus的最简单的应用,没有涉及事件处理的不同方法,也没有涉及事件的类型,接下来会继续写两篇博客,详细讲事件注册和事件分发。
- EventBus 使用
- EventBus使用
- eventbus使用
- EventBus使用
- EventBus---使用
- EventBus使用
- EventBus 使用
- EventBus使用
- EventBus使用
- EventBus使用
- EventBus使用
- EventBus使用
- EventBus使用
- EventBus使用
- EventBus使用
- EventBus使用
- EventBus使用
- EventBus使用
- PHP中Session引起的脚本阻塞问题解决办法
- Java2下实现applet数字签名和认证
- linux gdb 断点设置以及使用
- 在xcode6.1和ios10.10.1环境下实现真机测试
- 南大软院大神养成计划--day18
- EventBus---使用
- 快速点击Altdialog多下弹出多个dialog问题
- Jquery_artDialog对话框弹出
- Android SlidingDrawer使用
- 1025解题--学习
- android View 事件分发
- 俞敏洪老师2014年底写的
- LOG 调试中的V、D、I、W、E
- ListView滑动到底部加载数据