EventBus主页面发送消息其他页面接收消息

今天心血来潮 怀着激动的心情来给码友们甩一个小博客!!

 

 

概念、优点等什么的我就不说了网上一箩筐

废话不说了 直接甩代码

 

1.导入依赖

 
 
compile 'org.greenrobot:eventbus:3.0.0'

 

 
 
主页面发送消息:
 
public class MainActivity extends AppCompatActivity { private EditText etName; private EditText etPwd; private Button butLogin; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); butLogin = (Button) findViewById(R.id.butLogin); etName = (EditText) findViewById(R.id.etName); etPwd = (EditText) findViewById(R.id.etPwd); butLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String name = etName.getText().toString(); String pwd = etPwd.getText().toString(); Toast.makeText(MainActivity.this,name+pwd,Toast.LENGTH_SHORT).show(); EventBus.getDefault().postSticky(new MyData(name,pwd)); Intent in = new Intent(MainActivity.this,Main2Activity.class); startActivity(in); } }); } @Override protected void onDestroy() { super.onDestroy(); EventBus.getDefault().unregister(this); } } 

 

 

第二个页面 接收消息(注意:在哪里接收消息就得在哪里注册)

 

注册

EventBus.getDefault().register(this);
public class Main2Activity extends AppCompatActivity {

    String sName,sPwd;
    TextView name,pwd;
    Button button;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        //注册
        EventBus.getDefault().register(this);

        button = (Button) findViewById(R.id.but);
        name = (TextView) findViewById(R.id.tvName);
        pwd  = (TextView) findViewById(R.id.tvPwd);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                name.setText(sName);
                pwd.setText(sPwd);

            }
        });
        
    }

    //接收消息
    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    public void onEventMainThread(MyData data){

        sName = data.getsName();
        sPwd = data.getsPwd();

        Log.d("data","====" + sName + sPwd);

    }
}

 

这是我的参数事件类

 

public class MyData {
    private String name;
    private String pwd;

    public MyData(String sName,String sPwd) {
        name = sName;
        pwd  = sPwd;
    }

    public String getsName() {
        return name;
    }

    public String getsPwd() {
        return pwd;
    }
}


效果图 ↓↓↓

EventBus主页面发送消息其他页面接收消息_第1张图片 

EventBus主页面发送消息其他页面接收消息_第2张图片
EventBus主页面发送消息其他页面接收消息_第3张图片

 

你可能感兴趣的:(EventBus主页面发送消息其他页面接收消息)