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

转载请注明出处:https://blog.csdn.net/mr_leixiansheng/article/details/79898864


不详解,只介绍用法(包括主线程调用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


详解可参考一下网址

https://blog.csdn.net/itachi85/article/details/52205464








阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Mr_Leixiansheng/article/details/79898864
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭