EventBus事件总线(个人理解监听回调,勿喷)

转载请注明出处:EventBus事件总线(个人理解监听回调,勿喷)_Mr_Leixiansheng的博客-CSDN博客

不详解,只介绍用法(包括主线程调用EventBus,子线程调用EventBus)

步骤:

1、需要接收事件处注册EventBus,如在Main中注册

EventBus.getDefault().register(this);

2、新建事件类

3、需要发送事件发送发送事件,如SecondActivity中发送

EventBus.getDefault().post(new SecondFButtonClickEvent(mEtInput.getText().toString()));

4、需要接收事件处注册实现事件接收(需要手动打出来,注意@Subscribe注释)

 @Subscribe
    public void onEvent(SecondFButtonClickEvent event) {
        // UI updates must run on MainThread
        mTextView.setText(event.msg);
    }

*子线程中返回的时间需要在主线程中操作时需要声明位置

@Subscribe(threadMode = ThreadMode.MAIN)

代码如下:

1、事件接收处

package com.example.leixiansheng.eventbustest;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

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

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.button)
    Button mButton;
    @BindView(R.id.textView)
    TextView mTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);

        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, SecondActivity.class));
            }
        });
        mTextView.setText("等待EventBus回传");
    }

    @Subscribe
    public void onEvent(SecondFButtonClickEvent event) {
        // UI updates must run on MainThread
        mTextView.setText(event.msg);
    }

    @Subscribe
    public void onEvent(SecondOnCreateEvent event) {
        Log.i("TAG", event.msg);
    }

    @Subscribe
    public void onEvent(SecondOnDestroyEvent event) {
        Log.i("TAG", event.msg);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}

布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.leixiansheng.eventbustest.MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="TextView" />
</LinearLayout>

2、事件发送处

package com.example.leixiansheng.eventbustest;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

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

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Leixiansheng on 2018/4/9.
 */

public class SecondActivity extends AppCompatActivity {

    @BindView(R.id.btn_back)
    Button mBtnBack;
    @BindView(R.id.et_input)
    EditText mEtInput;
    @BindView(R.id.btn_thread)
    Button mBtnThread;
    @BindView(R.id.iv_cover)
    ImageView mIvCover;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        EventBus.getDefault().post(new SecondOnCreateEvent("second onCreate"));

        mBtnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String str = mEtInput.getText().toString();
                boolean isStrEmpty = str.isEmpty() || (str.length() < 0);
                if (isStrEmpty) {
                    Toast.makeText(SecondActivity.this, "请输入返回内容", Toast.LENGTH_SHORT).show();
                    return;
                }
                Toast.makeText(SecondActivity.this, "已经返回数据到主页面", Toast.LENGTH_SHORT).show();
                //通过EventBus.getDefault().post();向主页传输数据
                EventBus.getDefault().post(new SecondFButtonClickEvent(mEtInput.getText().toString()));
                mBtnBack.setEnabled(false);

                new Timer().schedule(new TimerTask() {
                    @Override
                    public void run() {
                        finish();
                    }
                }, 1000);
            }
        });

        mBtnThread.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               new Thread(new Runnable() {
                   @Override
                   public void run() {
                       try {
                           Thread.sleep(2000);
                           EventBus.getDefault().post(new RefreshCoverEvent(R.mipmap.ic_launcher));
                       } catch (InterruptedException e) {
                           e.printStackTrace();
                       }
                   }
               }).start();
            }
        });
    }

    /**
     * 子线程数据加载完成后在UI界面刷新时,需要选择threadMode
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(RefreshCoverEvent event) {
        mIvCover.setImageResource(event.ivId);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().post(new SecondOnCreateEvent("second onDestroy"));
        EventBus.getDefault().unregister(this);
    }
}

布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.leixiansheng.eventbustest.MainActivity">

    <Button
        android:id="@+id/btn_back"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="back"/>

    <EditText
        android:id="@+id/et_input"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:hint="请输入回传内容"
        android:gravity="left"
        android:textColorHint="#ffffffff"
        android:background="#000000"
        android:textColor="#ffffffff" />

    <Button
        android:id="@+id/btn_thread"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Create Thread"
        android:textAllCaps="false"/>

    <ImageView
        android:id="@+id/iv_cover"
        android:layout_gravity="center"
        android:layout_width="100dp"
        android:layout_height="100dp" />
</LinearLayout>

3、自定义的事件类

package com.example.leixiansheng.eventbustest;

/**
 * Created by Leixiansheng on 2018/4/9.
 */

public class SecondFButtonClickEvent {
    public String msg;

    public SecondFButtonClickEvent(String msg) {
        this.msg = msg;
    }
}

package com.example.leixiansheng.eventbustest;

/**
 * Created by Leixiansheng on 2018/4/9.
 */

public class SecondOnCreateEvent {
    public String msg;

    public SecondOnCreateEvent(String msg) {
        this.msg = msg;
    }
}

package com.example.leixiansheng.eventbustest;

/**
 * Created by Leixiansheng on 2018/4/9.
 */

public class SecondOnDestroyEvent {
    public String msg;

    public SecondOnDestroyEvent(String msg) {
        this.msg = msg;
    }
}


Log打印信息如下

04-11 16:14:29.411 27433-27433/com.example.leixiansheng.eventbustest I/TAG: second onCreate
04-11 16:15:18.991 27433-27433/com.example.leixiansheng.eventbustest I/TAG: second onDestroy

详解可参考一下网址

Android事件总线(一)EventBus3.0用法全解析_刘望舒的博客-CSDN博客





 


 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在 Nuxt2 中使用 eventBus 事件总线,可以通过以下步骤实现: 1. 创建一个 eventBus.js 文件 在项目的根目录中,创建一个 eventBus.js 文件,代码如下: ```javascript import Vue from 'vue'; export const eventBus = new Vue(); ``` 这里使用了 Vue 的实例来创建 eventBus,并且将它导出,这样就可以在项目中的任何地方使用它了。 2. 在需要使用 eventBus 的组件中引入 eventBus 在需要使用 eventBus 的组件中,可以使用以下代码来引入 eventBus: ```javascript import {eventBus} from '@/eventBus.js'; ``` 这里的 @ 表示项目的根目录,如果 eventBus.js 文件不在根目录中,那么需要改成相应的路径。 3. 使用 eventBus 发送事件 在需要发送事件的地方,可以使用以下代码来发送事件: ```javascript eventBus.$emit('eventName', data); ``` 这里的 eventName 是事件的名称,data 是传递的数据。 4. 使用 eventBus 监听事件 在需要监听事件的地方,可以使用以下代码来监听事件: ```javascript eventBus.$on('eventName', (data) => { // 处理事件 }); ``` 这里的 eventName 是事件的名称,data 是传递的数据。事件触发后,会执行函数中的代码。 总结: 以上就是在 Nuxt2 中使用 eventBus 事件总线的方法,通过使用 eventBus,可以在组件之间方便地进行通信。需要注意的是,eventBus 的使用需要谨慎,过多的使用可能会导致代码的可读性和维护性降低。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值