日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

【EventBus】EventBus 使用示例 ( 最简单的 EventBus 示例 )

發(fā)布時間:2025/6/17 编程问答 43 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【EventBus】EventBus 使用示例 ( 最简单的 EventBus 示例 ) 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

文章目錄

  • 一、導(dǎo)入依賴
  • 二、注冊 EventBus
  • 三、發(fā)送 EventBus 事件
  • 四、完整代碼示例
  • 五、源碼地址





一、導(dǎo)入依賴



在 Module 下的 build.gradle 中導(dǎo)入 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);}



三、發(fā)送 EventBus 事件



點(diǎn)擊按鈕 , 通過 EventBus 發(fā)送消息 ;

textView = findViewById(R.id.textView);// 設(shè)置點(diǎn)擊事件, 點(diǎn)擊后發(fā)送消息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);// 設(shè)置點(diǎn)擊事件, 點(diǎn)擊后發(fā)送消息textView.setOnClickListener((View view)->{EventBus.getDefault().post("Hello EventBus !");});// 首先注冊訂閱 EventBusEventBus.getDefault().register(this);}/*** 使用 @Subscribe 注解修飾處理消息的方法* 該方法必須是 public void 修飾的* 只有一個參數(shù) , 參數(shù)類型隨意* 調(diào)用 EventBus.getDefault().post 即可發(fā)送消息到該方法進(jìn)行處理* @param msg*/@Subscribepublic void onMessgeEvent(String msg){textView.setText(msg);}@Overrideprotected void onDestroy() {super.onDestroy();// 取消注冊EventBus.getDefault().unregister(this);} }

運(yùn)行效果 : 點(diǎn)擊按鈕后發(fā)送消息 , 處理消息的 onMessgeEvent 方法中 , 接收到消息 , 將按鈕文本變?yōu)?“Hello EventBus !” ;





五、源碼地址



GitHub : https://github.com/han1202012/EventBus_Demo

總結(jié)

以上是生活随笔為你收集整理的【EventBus】EventBus 使用示例 ( 最简单的 EventBus 示例 )的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。