EventBus传值

  依赖:

implementation 'org.greenrobot:eventbus:3.0.0'

详细内容:https://www.jianshu.com/p/f9ae5691e1bb

1.布局




   

2.需要写一个Message类  传值

package com.bw.ymy.text1_eventbus;

public class MessageEvent {
    private String message;
    public  MessageEvent(String message){
        this.message=message;
    }
    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

}

3.主页面内容

package com.bw.ymy.text1_eventbus;

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

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

public class MainActivity extends AppCompatActivity {
    private Button mbutton;
    private TextView mtext;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //首先需要注册事件
        EventBus.getDefault().register(this);
        //获取资源id
        mbutton=findViewById(R.id.button);
        mtext=findViewById(R.id.text);
        mtext.setText("今天是礼拜三");
        //点击跳转
        mbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(MainActivity.this,Main2Activity.class);
                startActivity(intent);
            }
        });
    }
    //
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void  Evect(MessageEvent messageEvent)
    {
        mtext.setText(messageEvent.getMessage());
    }
    //解除注册
    @Override
    protected void onDestroy() {
        super.onDestroy();
       if(EventBus.getDefault().isRegistered(this))
       {
           EventBus.getDefault().unregister(this);
       }
    }
}

4.跳转到页面的布局



    

5.主页面

package com.bw.ymy.text1_eventbus;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import org.greenrobot.eventbus.EventBus;

public class Main2Activity extends AppCompatActivity {
    private Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        button=findViewById(R.id.button1);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().post(new MessageEvent("喜迎2019,发发发"));
                //销毁
                finish();
            }
        });
    }
}

效果图:

点击跳转 进去 再点击 把值携带过来

EventBus传值_第1张图片

你可能感兴趣的:(EventBus传值)