zoukankan      html  css  js  c++  java
  • Android EventBus使用大全

    添加依赖
    implementation 'org.greenrobot:eventbus:3.1.1'

    public class HuaDongActivity extends Activity {

    private Button nianxing;
    // 用来判断是否需要停止事件的继续分发
    private boolean stopDelivery = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_hua_dong);
    nianxing = findViewById(R.id.nianxing);
    nianxing.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    stopDelivery = true;
    EventBus.getDefault().postSticky(MessageWrap.getInstance("哈哈哈哈"));
    }
    });
    EventBus.getDefault().register(HuaDongActivity.this);

    EventBus.getDefault().post(MessageWrap.getInstance("哈哈哈"));


    }


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

    /**
    * 注册普通事件
    * @param wrap
    */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void MyMessage(MessageWrap wrap){
    Toast.makeText(this,wrap.message.toString(),Toast.LENGTH_LONG).show();
    }


    /**
    * 注册粘性事件
    * 粘性事件表示,我可以直接发送,等到我想要接收的时候,我在订阅他
    * @param message
    */
    // @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    // public void onGetStickyEvent(MessageWrap message) {
    // String txt = "Sticky event: " + message.message;
    // Toast.makeText(this,txt,Toast.LENGTH_LONG).show();
    // }

    @Subscribe(threadMode = ThreadMode.POSTING, priority = 0)
    public void onGetMessage(MessageWrap message) {
    Log.i("TAG","onGetMessage");
    Toast.makeText(this,message.message,Toast.LENGTH_LONG).show();
    }

    // 订阅方法,需要与上面的方法的threadMode一致,并且优先级略高
    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true, priority = 1)
    public void onGetStickyEvent(MessageWrap message) {
    Log.i("TAG","onGetStickyEvent");
    String txt = "Sticky event: " + message.message;
    Toast.makeText(this,txt,Toast.LENGTH_LONG).show();
    if (stopDelivery) {
    // 终止事件的继续分发
    EventBus.getDefault().cancelEventDelivery(message);
    }
    }
    }

    <?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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".HuaDongActivity">

    <Button
    android:id="@+id/nianxing"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="点击发送粘性事件"
    />

    </RelativeLayout>

    参考自https://www.jianshu.com/p/e7d5c7bda783,感觉大佬!

  • 相关阅读:
    java使用递归删除非空目录
    关于Java日期的两道例题
    equals和==的区别
    从键盘读入个数不确定的整数,并判断读入的正数和负数的个数,输入为0时结束程序。
    输出所有的水仙花数
    99乘法表
    switch
    next()、nextInt()
    流程控制
    Scanner从键盘输入
  • 原文地址:https://www.cnblogs.com/xiaoxiaing/p/11983923.html
Copyright © 2011-2022 走看看