为什么我的新片段无法订阅otto [英] Why my new fragment can't subscribe otto

查看:92
本文介绍了为什么我的新片段无法订阅otto的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在活动中发表了一篇文章,并且在第一个片段BlankFragment中效果很好,但是,当我尝试用BlackFragment2替换BlankFragment并进行相同的订阅时,它不再能订阅了,这是代码

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:

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和BlankFragment2使用相同的代码:

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());
}

有人可以帮我吗?

推荐答案

使用commitNow()代替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();

这篇关于为什么我的新片段无法订阅otto的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆