【EventBus】EventBus 使用示例 ( 最简单的 EventBus 示例 )
生活随笔
收集整理的這篇文章主要介紹了
【EventBus】EventBus 使用示例 ( 最简单的 EventBus 示例 )
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 一、導入依賴
- 二、注冊 EventBus
- 三、發送 EventBus 事件
- 四、完整代碼示例
- 五、源碼地址
一、導入依賴
在 Module 下的 build.gradle 中導入 EventBus 依賴 ;
implementation 'org.greenrobot:eventbus:3.2.0'二、注冊 EventBus
在 onCreate 注冊 EventBus ;
@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);// 首先注冊訂閱 EventBusEventBus.getDefault().register(this);}在 onDestory 中 取消注冊 EventBus ;
@Overrideprotected void onDestroy() {super.onDestroy();// 取消注冊EventBus.getDefault().unregister(this);}三、發送 EventBus 事件
點擊按鈕 , 通過 EventBus 發送消息 ;
textView = findViewById(R.id.textView);// 設置點擊事件, 點擊后發送消息textView.setOnClickListener((View view)->{EventBus.getDefault().post("Hello EventBus !");});四、完整代碼示例
package com.eventbus_demo;import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle; import android.view.View; import android.widget.TextView;import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe;public class MainActivity extends AppCompatActivity {private TextView textView;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);textView = findViewById(R.id.textView);// 設置點擊事件, 點擊后發送消息textView.setOnClickListener((View view)->{EventBus.getDefault().post("Hello EventBus !");});// 首先注冊訂閱 EventBusEventBus.getDefault().register(this);}/*** 使用 @Subscribe 注解修飾處理消息的方法* 該方法必須是 public void 修飾的* 只有一個參數 , 參數類型隨意* 調用 EventBus.getDefault().post 即可發送消息到該方法進行處理* @param msg*/@Subscribepublic void onMessgeEvent(String msg){textView.setText(msg);}@Overrideprotected void onDestroy() {super.onDestroy();// 取消注冊EventBus.getDefault().unregister(this);} }
運行效果 : 點擊按鈕后發送消息 , 處理消息的 onMessgeEvent 方法中 , 接收到消息 , 將按鈕文本變為 “Hello EventBus !” ;
五、源碼地址
GitHub : https://github.com/han1202012/EventBus_Demo
總結
以上是生活随笔為你收集整理的【EventBus】EventBus 使用示例 ( 最简单的 EventBus 示例 )的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【EventBus】EventBus 事
- 下一篇: 【EventBus】Subscribe