今天就跟大家聊聊有關(guān)Android中使用eventbus3.0實(shí)現(xiàn)fragment通信,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
1.概述
在之前的博文中簡(jiǎn)單介紹過如何實(shí)現(xiàn)fragment之間的信息交互:《Android中Fragment與Activity之間的交互(兩種實(shí)現(xiàn)方式)》,今天繼續(xù)給大家介紹一種可以實(shí)現(xiàn)此效果的另外一種方式EventBus。(相比于handler,接口回調(diào),bundle傳參,這個(gè)簡(jiǎn)單好用到哭)
EventBus是Android下高效的發(fā)布/訂閱事件的消息總線。作用是可以代替?zhèn)鹘y(tǒng)的Intent,Handler,Broadcast或接口函數(shù)在Fragment、Activity、Service、線程之間傳遞數(shù)據(jù)進(jìn)行通信,執(zhí)行方法。做為消息總線,有三個(gè)主要元素:
(1)Event:事件
(2)Subscriber:事件訂閱者,接受特定的事件
(3)Publisher:事件發(fā)布者,用于通知Subscriber有事件發(fā)生
結(jié)合EventBus以上的三個(gè)元素,我們也可以稱其為一種觀察者設(shè)計(jì)模式。
EventBus 官網(wǎng)鏈接http://greenrobot.org/eventbus/
EventBus GitHub鏈接https://github.com/greenrobot/EventBus
前期相關(guān)博文鏈接:
Android中Fragment與Activity之間的交互(兩種實(shí)現(xiàn)方式)
Android中Fragment的兩種創(chuàng)建方式
2.Demo示例
(1)示例中左側(cè)的按鈕,潘侯爺與碧空海觸發(fā)的事件為EventBus的普通事件發(fā)布
(2)左側(cè)粘性事件按鈕發(fā)布的為粘性事件
3.實(shí)現(xiàn)步驟
本次Demo架構(gòu):
3.1導(dǎo)依賴包
使用AndroidStudio2.2。仍然采用在build.gradle下中dependencies下直接添加如下代碼:
compile 'org.greenrobot:eventbus:3.0.0'
同步后完成依賴添加。
3.2布局文件
(1)layout中主布局文件,activity_main.xml文件
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" tools:context="com.mly.panhouye.eventbustest.MainActivity"> <LinearLayout android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:orientation="vertical" android:background="#6f6669"> <Button android:layout_gravity="center_horizontal" android:id="@+id/panhouye" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="ŋ" /> <Button android:layout_gravity="center_horizontal" android:id="@+id/bikonghai" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="̿պ" /> <Button android:layout_gravity="center_horizontal" android:id="@+id/postSticky" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="ճДʂ" /> </LinearLayout> <FrameLayout android:id="@+id/framelayout" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="2"></FrameLayout> </LinearLayout>
網(wǎng)頁(yè)題目:Android中使用eventbus3.0實(shí)現(xiàn)fragment通信-創(chuàng)新互聯(lián)
新聞來源:http://chinadenli.net/article30/dechpo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供ChatGPT、網(wǎng)站制作、自適應(yīng)網(wǎng)站、網(wǎng)站內(nèi)鏈、網(wǎng)站導(dǎo)航、營(yíng)銷型網(wǎng)站建設(shè)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容
網(wǎng)頁(yè)設(shè)計(jì)公司知識(shí)