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傳參,這個簡單好用到哭)
EventBus是Android下高效的發(fā)布/訂閱事件的消息總線。作用是可以代替?zhèn)鹘y(tǒng)的Intent,Handler,Broadcast或接口函數(shù)在Fragment、Activity、Service、線程之間傳遞數(shù)據(jù)進(jìn)行通信,執(zhí)行方法。做為消息總線,有三個主要元素:
(1)Event:事件
(2)Subscriber:事件訂閱者,接受特定的事件
(3)Publisher:事件發(fā)布者,用于通知Subscriber有事件發(fā)生
結(jié)合EventBus以上的三個元素,我們也可以稱其為一種觀察者設(shè)計模式。
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對應(yīng)的java類,除了在其中關(guān)聯(lián)其對應(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對應(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();
}
/*個人建議在onResume注冊EventBus
*在可見可交互狀態(tài)下注冊,盡可能少的占用內(nèi)存
*/
@Override
protected void onResume() {
super.onResume();
EventBus.getDefault().register(this);
}
/*個人建議在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ā)布的粘性事件在其新訂閱者注冊后將會自動傳遞給新訂閱者,有時我們也需要移除粘性事件,以免它在傳遞下去。
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)用在同一個線程中,這是發(fā)布事件(這是默認(rèn)值)。事件傳遞意昧著最少的開銷,因?yàn)樗耆苊饬司€程切換。因此,這是推薦的模式,來處理簡單的任務(wù),如果是已知的完成是一個很短的時間,而不需要主線程。事件處理使用此模式必須迅速返回,以避免阻塞發(fā)布線程,這可能是主線程。
(2)MainThread:用戶將被調(diào)用在主線程(UI線程)。如果發(fā)布線程是主線程,事件處理程序方法將直接調(diào)用。使用此模式的事件處理程序必須快速返回,避免阻塞主線程。
(3)BackgrounThread:將在后臺線程中調(diào)用訂閱者。如果發(fā)布線程不是主線程,則事件處理程序方法將被在發(fā)布線程中直接調(diào)用。如果線程是主線程,eventbus采用單獨(dú)的一個后臺線程,將按順序調(diào)用所有的事件。使用此模式的事件處理程序應(yīng)嘗試快速返回,以避免阻塞后臺線程。
(4)Async:事件處理程序方法在一個單獨(dú)的線程中調(diào)用。這總是獨(dú)立于發(fā)布線程和主線程。發(fā)布事件從來不會等待使用這種模式的事件處理程序方法。事件處理程序方法使用此模式,如果他們的執(zhí)行可能需要一段時間,例如用于網(wǎng)絡(luò)訪問。避免觸發(fā)大量在同一時間運(yùn)行長時間運(yùn)行的異步處理程序方法以限制并發(fā)線程的數(shù)目。eventbus使用一個線程池來有效地重用已完成的異步事件處理程序通知的線程。
以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,同時也希望多多支持腳本之家!
相關(guān)文章
Android Dialog 設(shè)置字體大小的具體方法
這篇文章介紹了Android Dialog 設(shè)置字體大小的具體方法,希望能幫助到有同樣需求的朋友,可能我的方法不是最好的,也希望有朋友指點(diǎn)2013-09-09
Android性能優(yōu)化死鎖監(jiān)控知識點(diǎn)詳解
這篇文章主要為大家介紹了Android性能優(yōu)化死鎖監(jiān)控知識點(diǎn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-10-10
Android實(shí)現(xiàn)中軸旋轉(zhuǎn)特效 Android制作別樣的圖片瀏覽器
這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)中軸旋轉(zhuǎn)特效,制作別樣的圖片瀏覽器,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-11-11
Android編程之創(chuàng)建自己的內(nèi)容提供器實(shí)現(xiàn)方法
這篇文章主要介紹了Android編程之創(chuàng)建自己的內(nèi)容提供器實(shí)現(xiàn)方法,結(jié)合具體實(shí)例形式分析了Android創(chuàng)建內(nèi)容提供器的原理、步驟與相關(guān)操作技巧,需要的朋友可以參考下2017-08-08
詳解Android應(yīng)用開發(fā)中Intent的作用及使用方法
這篇文章主要介紹了Android應(yīng)用開發(fā)中Intent的作用與用法,包括如何激活A(yù)ctivity組件與Intent的投遞等,需要的朋友可以參考下2016-03-03
Android Intent實(shí)現(xiàn)頁面跳轉(zhuǎn)的方法示例
本篇文章主要介紹了Android Intent實(shí)現(xiàn)頁面跳轉(zhuǎn)的方法示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-03-03

