问题
I have made a post in my activity, and it works well in the first fragment BlankFragment, however, when I tried to replace BlankFragment with BlackFragment2, and do the same subscribe, it can't subscribe anymore, here is the code.
MainActivity:
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().add(R.id.fr1, new BlankFragment()).commit();
button = (Button)findViewById(R.id.btn);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
BusStation.getBus().post(new Message("hellworld"));
}
});
btn2 = (Button)findViewById(R.id.btn2);
btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentManager fragmentManager1 = getSupportFragmentManager();
fragmentManager1.beginTransaction().replace(R.id.fr1, new BlankFragment2()).commit();
BusStation.getBus().post(new Message("zhengzhi zhou"));
}
});
}
BlankFragment and BlankFragment2 are using the same code:
@Override
public void onResume() {
super.onResume();BusStation.getBus().register(this);
}
@Override
public void onPause() {
super.onPause();
BusStation.getBus().unregister(this);
}
@Subscribe
public void receiveMsg(Message msg){
textView.setText(msg.getMsg());
}
Can anyone help me with this?
回答1:
Use commitNow()
instead Of commit()
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
// Replace the contents of the container with the new fragment
ft.replace(R.id.fragment_place, fragment);
// or ft.add(R.id.your_placeholder, new FooFragment());
// Complete the changes added above
ft.commitNow();
来源:https://stackoverflow.com/questions/46103119/why-my-new-fragment-cant-subscribe-otto