我试图在活动和片段之间使用greenrobot传递数据,但是我找不到一个合适的教程来详细说明它是如何做的.根据我到目前为止所读到的内容,我写了一些类似的东西,但它不起作用.我可以使用绿色机器人将数据传递给尚未初始化的活动或片段吗?
主要活动 :
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); EventBus.getDefault().post(new String("We are the champions")); Intent intent = new Intent("com.test.Activity_Lessons"); startActivity(intent); }
Activity_Lessons:
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Some initializations EventBus.getDefault().register(this); //Other Stuff } public void onEventMainThread(String s){ Toast.makeText(getActivity(), s, Toast.LENGTH_LONG).show(); }
永远不会在这里调用事件处理程序.我做错了什么?
EventBus有两种发布和注册事件的方法.如果活动或片段尚未初始化,我们可以使用registerSticky和postSticky而不是注册和发布.
这是我自己的更正代码:
主要活动 :
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); EventBus.getDefault().postSticky(new String("We are the champions")); Intent intent = new Intent("com.test.Activity_Lessons"); startActivity(intent); }
Activity_Lessons:
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Some initializations EventBus.getDefault().registerSticky(this); //Other Stuff } public void onEventMainThread(String s){ Toast.makeText(getActivity(), s, Toast.LENGTH_LONG).show(); }