1. 程式人生 > >EventBus兩個Activity傳值

EventBus兩個Activity傳值

EventBus是針一款對Android的釋出/訂閱事件匯流排。它可以讓我們很輕鬆的實現在Android各個元件之間傳遞訊息,並且程式碼的可讀性更好,耦合度更低。

依賴:compile ‘org.greenrobot:eventbus:3.0.0’

  • 1.1MainAcivity主方法
public class MainActivity extends AppCompatActivity {

    //註解
    @ViewInject(R.id.onbut)
    private Button but;
    private TextView ontv;

    @Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ontv = (TextView) findViewById(R.id.ontv); //註冊EventBus EventBus.getDefault().register(this); } public void onButton(View v){ Intent intent = new
Intent(MainActivity.this, SecondActivity.class); startActivity(intent); } //特別重要 @Subscribe(threadMode = ThreadMode.MAIN) @Subscribe(threadMode = ThreadMode.MAIN) public void onEventThread(FirstEvent event){ String msg = "onEventThread已經收到了訊息"+event.getmEvent(); ontv.setText(msg); Toast.makeText(this
,msg,Toast.LENGTH_SHORT).show(); } @Override protected void onDestroy() { super.onDestroy(); //反註冊EventBus EventBus.getDefault().unregister(this); } }
  • 1.2、SecondeActivity第二個頁面
public class SecondActivity extends Activity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second);

    }
    public void onPlay(View v){
        EventBus.getDefault().post(new FirstEvent("FirstEvent btn clicked222"));
    }

}

1.3、FirstEvent的一個方法

public class FirstEvent {
    private String mEvent;

    public String getmEvent() {
        return mEvent;
    }

    public void setmEvent(String mEvent) {
        this.mEvent = mEvent;
    }

    public FirstEvent(String mEvent){
        this.mEvent = mEvent;
    }
}