国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

安卓使用EventBus實現消息傳遞

2019-11-09 14:57:58
字體:
來源:轉載
供稿:網友

什么是EventBus

EventBus是一個 發布/訂閱 模式的消息總線庫,它簡化了應用程序內各組件間、組件與后臺線程間的通信,解耦了事件的發送者和接收者,避免了復雜的、易于出錯的依賴及生命周期問題,可以使我們的代碼更加簡潔、健壯。EventBus 用于各組件通信,那么用于 fragment 之間的通信就非常合適了。

1、基本框架搭建

想必大家從一個Activity跳轉到第二個Activity的程序應該都會寫,這里先稍稍把兩個Activity跳轉的代碼建起來。后面再添加EventBus相關的玩意。

MainActivity布局(activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"      xmlns:tools="http://schemas.android.com/tools"      android:layout_width="match_parent"      android:layout_height="match_parent"      android:orientation="vertical">            <Button           android:id="@+id/btn_try"          android:layout_width="match_parent"          android:layout_height="wrap_content"          android:text="btn_bty"/>      <TextView           android:id="@+id/tv"          android:layout_width="wrap_content"          android:layout_height="match_parent"/>    </LinearLayout> 新建一個Activity,SecondActivity布局(activity_second.xml)

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"      xmlns:tools="http://schemas.android.com/tools"      android:layout_width="match_parent"      android:layout_height="match_parent"      android:orientation="vertical"      tools:context="com.harvic.try_eventbus_1.SecondActivity" >        <Button           android:id="@+id/btn_first_event"          android:layout_width="match_parent"          android:layout_height="wrap_content"          android:text="First Event"/>    </LinearLayout>  MainActivity.java (點擊btn跳轉到第二個Activity)
public class MainActivity extends Activity {        Button btn;        @Override      PRotected void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          setContentView(R.layout.activity_main);            btn = (Button) findViewById(R.id.btn_try);            btn.setOnClickListener(new View.OnClickListener() {                @Override              public void onClick(View v) {                  // TODO Auto-generated method stub                  Intent intent = new Intent(getapplicationContext(),                          SecondActivity.class);                  startActivity(intent);              }          });      }    }  到這,基本框架就搭完了,下面開始按步驟使用EventBus了。

2、新建一個類FirstEvent

package com.harvic.other;    public class FirstEvent {        private String mMsg;      public FirstEvent(String msg) {          // TODO Auto-generated constructor stub          mMsg = msg;      }      public String getMsg(){          return mMsg;      }  } 

3、在要接收消息的頁面注冊EventBus:

在上面的GIF圖片的演示中,大家也可以看到,我們是要在MainActivity中接收發過來的消息的,所以我們在MainActivity中注冊消息。

通過我們會在OnCreate()函數中注冊EventBus,在OnDestroy()函數中反注冊。所以整體的注冊與反注冊的代碼如下:

package com.example.tryeventbus_simple;    import com.harvic.other.FirstEvent;    import de.greenrobot.event.EventBus;  import android.app.Activity;  import android.content.Intent;  import android.os.Bundle;  import android.util.Log;  import android.view.View;  import android.widget.Button;  import android.widget.TextView;  import android.widget.Toast;    public class MainActivity extends Activity {        Button btn;      TextView tv;        @Override      protected void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          setContentView(R.layout.activity_main);                  //注冊EventBus          EventBus.getDefault().register(this);            btn = (Button) findViewById(R.id.btn_try);          tv = (TextView)findViewById(R.id.tv);            btn.setOnClickListener(new View.OnClickListener() {                @Override              public void onClick(View v) {                  // TODO Auto-generated method stub                  Intent intent = new Intent(getApplicationContext(),                          SecondActivity.class);                  startActivity(intent);              }          });      }      @Override      protected void onDestroy(){          super.onDestroy();          EventBus.getDefault().unregister(this);//反注冊EventBus      }  }  

4、發送消息

發送消息是使用EventBus中的Post方法來實現發送的,發送過去的是我們新建的類的實例!

EventBus.getDefault().post(new FirstEvent("FirstEvent btn clicked"));  完整的SecondActivity.Java的代碼如下:

package com.example.tryeventbus_simple;    import com.harvic.other.FirstEvent;    import de.greenrobot.event.EventBus;  import android.app.Activity;  import android.os.Bundle;  import android.view.View;  import android.widget.Button;    public class SecondActivity extends Activity {      private Button btn_FirstEvent;        @Override      protected void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          setContentView(R.layout.activity_second);          btn_FirstEvent = (Button) findViewById(R.id.btn_first_event);            btn_FirstEvent.setOnClickListener(new View.OnClickListener() {                @Override              public void onClick(View v) {                  // TODO Auto-generated method stub                  EventBus.getDefault().post(                          new FirstEvent("FirstEvent btn clicked"));              }          });      }  }  

5、接收消息

接收消息時,我們使用EventBus中最常用的onEventMainThread()函數來接收消息,具體為什么用這個,我們下篇再講,這里先給大家一個初步認識,要先能把EventBus用起來先。

在MainActivity中重寫onEventMainThread(FirstEvent event),參數就是我們自己定義的類:

在收到Event實例后,我們將其中攜帶的消息取出,一方面Toast出去,一方面傳到TextView中;

public void onEventMainThread(FirstEvent event) {        String msg = "onEventMainThread收到了消息:" + event.getMsg();      Log.d("harvic", msg);      tv.setText(msg);      Toast.makeText(this, msg, Toast.LENGTH_LONG).show();  }
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 光山县| 浪卡子县| 五原县| 锡林浩特市| 会东县| 邹城市| 湖南省| 大宁县| 清水县| 临江市| 湟中县| 泽州县| 武穴市| 涟水县| 逊克县| 宿迁市| 公主岭市| 怀仁县| 杭州市| 灵川县| 汪清县| 桂阳县| 杭锦旗| 康乐县| 京山县| 岐山县| 西乌珠穆沁旗| 澄迈县| 建德市| 新邵县| 南华县| 合阳县| 隆子县| 谢通门县| 麻栗坡县| 修武县| 奉贤区| 平昌县| 东乡族自治县| 体育| 正定县|