问题,AppCompatActivity如何使用EventBus与FragmentActivity通信?
发现,FragmentActivity可以与AppCompatActivity进行通信并调用onEvent方法,但是如果将通信路径切换为与FragmentActivity进行通信的AppCompatActivity,则永远不会调用onEvent方法。
public class MainActivity extends AppCompatActivity{
private String data;
@Override protected void onCreate{
data = "private String data from MainActivity";
EventBus.getDefault().postSticky(data);
}
}
public class AccountFade extends FragmentActivity{
private String mAccountFadeData;
@Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
public void onEvent(String s){
Toast.makeText(this, "private String mAccountFadeData from MainActivity", Toast.LENGTH_LONG).show();
this.mAccountFadeData = s;
}
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EventBus.getDefault().register(this);
}
@Override public void onDestroy(){
EventBus.getDefault().unregister(this);
super.onDestroy();
}
}
答案 0 :(得分:1)
您必须创建包含一个String变量的类,并通过EventBus触发该类。
所以首先创建这样的类
public class DataChangeEvent {
private String data;
public DataChangeEvent(String data) {
this.data = data;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
}
现在将其用于您的活动
在活动中发帖:
EventBus.getDefault().postSticky(new DataChangeEvent(data));
获取FragmentActivity:
@Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
public void onEvent(DataChangeEvent event){
Toast.makeText(this, "private String mAccountFadeData from MainActivity", Toast.LENGTH_LONG).show();
this.mAccountFadeData = event.getData();
}