EventBus粘性事件简单应用


//依赖  compile 'org.greenrobot:eventbus:3.0.0'

//在Main里面写一个点击事件

第一行是要发送的内容括号里是new了一个类

 EventBus.getDefault().postSticky(new EventBusStickyMessage("我是粘性事件");
 Intent intent = new Intent(MainActivity.this, Main2Activity.class);
 startActivity(intent);

//进行传参的类  EventBusStickyMessage

public class EventBusStickyMessage {
    public String string;
    public EventBusStickyMessage(String string){
        this.string=string;
    }
    
}


//跳转的Main2

public class Main2Activity extends AppCompatActivity {
    private TextView tv;
    boolean flag= true;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        tv = (TextView) findViewById(R.id.tv);
    }
    public void Js(View view){
        if(flag){
            EventBus.getDefault().register(this);
            flag = false;
        }
    }
    //切换到主线程中
    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    public void ReceviceMessage(EventBusStickyMessage eventBusStickyMessage){
        tv.setText(eventBusStickyMessage.string);
    }

    @Override
    protected void onDestroy() {
        //移除所有的粘性事件
        EventBus.getDefault().removeAllStickyEvents();
        //解除注册
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}

//Main2布局一个button一个textview,点击btn接收值设置到textview上




你可能感兴趣的:(常用)