Android中使用開源框架eventbus3.0實(shí)現(xiàn)fragment之間的通信交互
1.概述
在之前的博文中簡單介紹過如何實(shí)現(xiàn)fragment之間的信息交互:《Android中Fragment與Activity之間的交互(兩種實(shí)現(xiàn)方式)》,今天繼續(xù)給大家介紹一種可以實(shí)現(xiàn)此效果的另外一種方式EventBus。(相比于handler,接口回調(diào),bundle傳參,這個(gè)簡單好用到哭)
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>
(2)layout中右側(cè)的fragment布局文件fragment_msg.xml文件
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/tv" android:layout_width="match_parent" android:layout_height="match_parent" android:text="no data" android:textSize="50sp" android:gravity="center_horizontal"/> </LinearLayout>
(3)layout中粘性事件的演示界面布局activity_main2.xml文件
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main2" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.mly.panhouye.eventbustest.Main2Activity"> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:textSize="30sp" android:gravity="center_horizontal" android:id="@+id/tv" android:text="no data"/> </RelativeLayout>
3.3java實(shí)現(xiàn)代碼
(1)自定義事件類
本次演示最簡單事件的發(fā)布,事件僅發(fā)布字符串?dāng)?shù)據(jù),MessageEvent.java文件如下:
package com.mly.panhouye.eventbustest; /** * Created by panchengjia on 2017/2/19 0019. */ public class MessageEvent { String data; public MessageEvent(String data) { this.data = data; } }
(2)MsgFragment.java
右側(cè)fragment對(duì)應(yīng)的java類,除了在其中關(guān)聯(lián)其對(duì)應(yīng)的fragment布局外,還需要添加修改fragment中文本的方法,如下:
package com.mly.panhouye.eventbustest; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; /** * Created by panchengjia on 2017/2/20 0020. */ public class MsgFragment extends Fragment { TextView tv; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_msg,container,false); tv = (TextView) view.findViewById(R.id.tv); return view; } public void setText(String message){ tv.setText(message); } }
(3)MainActivity.java
MainActivity.java對(duì)應(yīng)的布局為主布局,右側(cè)的fragment附屬于該布局,所以需要在該類中注冊EventBus,將當(dāng)前的Activity注冊為事件訂閱者,具體代碼如下:
package com.mly.panhouye.eventbustest; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; public class MainActivity extends AppCompatActivity implements View.OnClickListener { Button panhouye,bikonghai,postSticky; MsgFragment msgFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); panhouye= (Button) findViewById(R.id.panhouye); bikonghai= (Button) findViewById(R.id.bikonghai); postSticky= (Button) findViewById(R.id.postSticky); panhouye.setOnClickListener(this); bikonghai.setOnClickListener(this); postSticky.setOnClickListener(this); //添加fragment到右側(cè)的幀布局中 msgFragment = new MsgFragment(); getSupportFragmentManager().beginTransaction().add(R.id.framelayout,msgFragment).commit(); } /*個(gè)人建議在onResume注冊EventBus *在可見可交互狀態(tài)下注冊,盡可能少的占用內(nèi)存 */ @Override protected void onResume() { super.onResume(); EventBus.getDefault().register(this); } /*個(gè)人建議在onPause注冊EventBus(將當(dāng)前Activity注冊為事件訂閱者) *不影響功能的情況下提早解除注冊,盡可能少的占用內(nèi)存 */ @Override protected void onPause() { super.onPause(); EventBus.getDefault().unregister(this); } /** * 事件發(fā)布者(通過按鈕點(diǎn)擊事件進(jìn)行事件發(fā)布) * @param v */ @Override public void onClick(View v) { switch (v.getId()){ //(1)事件發(fā)布中所傳參數(shù)可以作為右側(cè)fragment文本的修改內(nèi)容 //(2)事件發(fā)布中所傳參數(shù)也可以用作事件訂閱者執(zhí)行方法的區(qū)分通知 case R.id.panhouye: EventBus.getDefault().post(new MessageEvent("潘侯爺")); break; case R.id.bikonghai: EventBus.getDefault().post(new MessageEvent("碧空海")); break; case R.id.postSticky: //粘性事件發(fā)布 EventBus.getDefault().postSticky(new MessageEvent("粘性事件")); startActivity(new Intent(this,Main2Activity.class)); break; } } /** * 事件訂閱者自定義的接收方法 * @param event */ @Subscribe(threadMode = ThreadMode.MAIN) public void onMessageEvent(MessageEvent event) { // //(1)將事件發(fā)布者發(fā)布的數(shù)據(jù)作為文本修改內(nèi)容 // msgFragment.setText(event.data); //(2)將事件發(fā)布者發(fā)布的數(shù)據(jù)作為方法執(zhí)行的區(qū)分 switch(event.data){ case "潘侯爺": msgFragment.setText("panhouye"); break; case "碧空海": msgFragment.setText("bikonghai"); break; } } }
(4)Main2Activity.java
注意:此布局作為粘性事件發(fā)布的訂閱者,同樣需要注冊EventBus
package com.mly.panhouye.eventbustest; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; public class Main2Activity extends AppCompatActivity { TextView tv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); tv = (TextView) findViewById(R.id.tv); } @Override protected void onResume() { super.onResume(); EventBus.getDefault().register(this); } @Override protected void onPause() { super.onPause(); EventBus.getDefault().unregister(this); } @Subscribe(threadMode = ThreadMode.MAIN,sticky = true) public void onMessageEvent(MessageEvent event) { // //(1)將事件發(fā)布者發(fā)布的數(shù)據(jù)作為文本修改內(nèi)容 tv.setText(event.data); //(2)將事件發(fā)布者發(fā)布的數(shù)據(jù)作為方法執(zhí)行的區(qū)分 // switch(event.data){ // case "粘性事件": // tv.setText("panhouye"); // break; // } } }
發(fā)布的粘性事件在其新訂閱者注冊后將會(huì)自動(dòng)傳遞給新訂閱者,有時(shí)我們也需要移除粘性事件,以免它在傳遞下去。
MessageEvent stickyEvent = EventBus.getDefault().getStickyEvent(MessageEvent.class); // Better check that an event was actually posted before if(stickyEvent != null) { // "Consume" the sticky event EventBus.getDefault().removeStickyEvent(stickyEvent); // Now do something with it } MessageEvent stickyEvent = EventBus.getDefault().removeStickyEvent(MessageEvent.class); // Better check that an event was actually posted before if(stickyEvent != null) { // Now do something with it }
4.線程模式
EventBus提供了四種線程模式:
(1)postThread:用戶將被調(diào)用在同一個(gè)線程中,這是發(fā)布事件(這是默認(rèn)值)。事件傳遞意昧著最少的開銷,因?yàn)樗耆苊饬司€程切換。因此,這是推薦的模式,來處理簡單的任務(wù),如果是已知的完成是一個(gè)很短的時(shí)間,而不需要主線程。事件處理使用此模式必須迅速返回,以避免阻塞發(fā)布線程,這可能是主線程。
(2)MainThread:用戶將被調(diào)用在主線程(UI線程)。如果發(fā)布線程是主線程,事件處理程序方法將直接調(diào)用。使用此模式的事件處理程序必須快速返回,避免阻塞主線程。
(3)BackgrounThread:將在后臺(tái)線程中調(diào)用訂閱者。如果發(fā)布線程不是主線程,則事件處理程序方法將被在發(fā)布線程中直接調(diào)用。如果線程是主線程,eventbus采用單獨(dú)的一個(gè)后臺(tái)線程,將按順序調(diào)用所有的事件。使用此模式的事件處理程序應(yīng)嘗試快速返回,以避免阻塞后臺(tái)線程。
(4)Async:事件處理程序方法在一個(gè)單獨(dú)的線程中調(diào)用。這總是獨(dú)立于發(fā)布線程和主線程。發(fā)布事件從來不會(huì)等待使用這種模式的事件處理程序方法。事件處理程序方法使用此模式,如果他們的執(zhí)行可能需要一段時(shí)間,例如用于網(wǎng)絡(luò)訪問。避免觸發(fā)大量在同一時(shí)間運(yùn)行長時(shí)間運(yùn)行的異步處理程序方法以限制并發(fā)線程的數(shù)目。eventbus使用一個(gè)線程池來有效地重用已完成的異步事件處理程序通知的線程。
以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來一定的幫助,同時(shí)也希望多多支持腳本之家!
相關(guān)文章
Android實(shí)現(xiàn)MVVM架構(gòu)數(shù)據(jù)刷新詳解流程
MVVM架構(gòu)模式,即Model-View-ViewModel三個(gè)層級(jí),MVVM模式出來的時(shí)間已經(jīng)很長了,網(wǎng)上關(guān)于MVVM模式的解析也有很多,我這里只說一下我自己的理解,基本上是和MVP模式相比較的一個(gè)差異2021-10-10Android實(shí)現(xiàn)Activity界面切換添加動(dòng)畫特效的方法
這篇文章主要介紹了Android實(shí)現(xiàn)Activity界面切換添加動(dòng)畫特效的方法,非常實(shí)用的技巧,需要的朋友可以參考下2014-08-08Android學(xué)習(xí)筆記之ActionBar Item用法分析
這篇文章主要介紹了Android學(xué)習(xí)筆記之ActionBar Item用法,結(jié)合實(shí)例形式分析了ActionBar Item的具體功能與相關(guān)使用技巧,需要的朋友可以參考下2017-05-05詳解Android使用Socket對(duì)大文件進(jìn)行加密傳輸
這篇文章主要介紹了詳解Android使用Socket對(duì)大文件進(jìn)行加密傳輸,使用Socket進(jìn)行文件傳輸過程時(shí),需要先進(jìn)行加密,有興趣的可以了解一下。2017-01-01Android自定義控件實(shí)現(xiàn)時(shí)間軸
這篇文章主要為大家詳細(xì)介紹了Android自定義控件實(shí)現(xiàn)時(shí)間軸,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-04-04Android編程之監(jiān)聽器用法實(shí)例分析
這篇文章主要介紹了Android編程之監(jiān)聽器用法,結(jié)合實(shí)例形式較為詳細(xì)的分析了Android監(jiān)聽器的功能及針對(duì)短信的監(jiān)聽與響應(yīng)操作技巧,需要的朋友可以參考下2016-01-01