EventBus简单使用(附demo)

本文详细介绍如何在Android应用中使用EventBus实现组件间的消息传递。通过实例演示了MainActivity作为订阅者接收来自Main2Activity发布者发送的颜色信息,并根据接收到的信息改变界面元素的背景颜色。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Demo功能:

MainActivity是订阅者,界面有两个按钮(一个按钮用于接收,一个用于跳转到Main2Activity)
Main2Activity是事件发布者,界面有两个按钮(一个用于发布红色背景信息,一个发布蓝色)。
MainActivityMain2Activity

Step1, Module app 导入 EventBus 包

    implementation 'org.greenrobot:eventbus:3.0.0'       

Step2,我用了ButterKnife来绑定控件,因此也需要导入一些包,在Module app 中

apply plugin: 'com.android.application'
android {
    compileSdkVersion 29
    buildToolsVersion "29.0.3"
    defaultConfig {
        applicationId "com.example.myapplication"
        minSdkVersion 24
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    compileOptions {               //ButterKnife配置文件
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'com.google.android.material:material:1.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

    implementation 'org.greenrobot:eventbus:3.0.0'                         //EventBus配置文件
    implementation 'com.jakewharton:butterknife:10.2.1'                    //ButterKnife配置文件
    annotationProcessor 'com.jakewharton:butterknife-compiler:10.2.1'      //ButterKnife配置文件


}

Step 4,新建实体类 ColorTypeMessage 用来传输颜色信息

public class ColorTypeMessage {

    private String colorType;

    public ColorTypeMessage(String colorType) {
        this.colorType = colorType;
    }

    public String getColorType() {
        return colorType;
    }

    public void setColorType(String colorType) {
        this.colorType = colorType;
    }
}

Setp 5,MainActivity代码

package com.example.myapplication;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * MainActivity是订阅者,订阅者需要注册EventBus事务,见下面代码
 */
public class MainActivity extends AppCompatActivity {

    @BindView(R.id.subscriber)
    Button subscriber;
    @BindView(R.id.go_activity2)
    Button goActivity2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);       //onCreate()注册EventBus事务
    }

    //当Main2Activity发出消息后,MainActivity在这个方法里面进行接受,
    // 由于Main2Activity发出消息时候,MainActivity不在运行态因此不能立刻接收,因此用粘性发送
    @Subscribe(threadMode = ThreadMode.MAIN,sticky =true)
    public void onChangeColorEvent(ColorTypeMessage colorTypeMessage) {
        if (colorTypeMessage.getColorType().equals("red")) {
            subscriber.setBackgroundColor(getResources().getColor(R.color.colorAccent));   //改变按钮背景颜色
        } else {
            subscriber.setBackgroundColor(getResources().getColor(R.color.blue));
        }
    }

    @OnClick({R.id.subscriber, R.id.go_activity2})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.subscriber:
                break;
            case R.id.go_activity2:
                Intent intent = new Intent(MainActivity.this, Main2Activity.class);
                startActivity(intent);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);             //onDestroy()解绑EventBus事务
    }
}

Step 6 ,Main2Activity代码

/**
 * Main2Activity为信息发布者
 */
public class Main2Activity extends AppCompatActivity {

    @BindView(R.id.become_red)
    Button becomeRed;
    @BindView(R.id.become_blue)
    Button becomeBlue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        ButterKnife.bind(this);
    }

    @OnClick({R.id.become_red, R.id.become_blue})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.become_red:
                EventBus.getDefault().postSticky(new ColorTypeMessage("red"));  //发出消息,粘性发送
                break;
            case R.id.become_blue:
                EventBus.getDefault().postSticky(new ColorTypeMessage("blue"));
                break;
        }
    }
}```

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值