Why my new fragment can't subscribe otto

孤街醉人 提交于 2020-01-05 04:01:49

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!