【问题标题】:How to use EventBus in fragment?如何在片段中使用 EventBus?
【发布时间】:2018-07-26 07:09:44
【问题描述】:

在我的应用程序中,我将fragment 用于Activity,并且我希望在将一个代码运行到fragment 时,调用Activity 中的一些代码。

我写了下面的代码,但是当加载数据时没有运行activity代码。!

片段代码:

    public void loadRecentPosts() {
        ApiUtils.getApiInterface().getRecentPosts(AppConstant.DEFAULT_PAGE).enqueue(new Callback<List<Post>>() {
            @Override
            public void onResponse(Call<List<Post>> call, Response<List<Post>> response) {
                if (response.isSuccessful()) {

                    if (!recentPostList.isEmpty()) {
                        recentPostList.clear();
                    }
                    recentPostList.addAll(response.body());
                    if (recentPostList.size() > 0) {
                        recentPostAdapter.notifyDataSetChanged();
                        EventBus.getDefault().post(new LoadMainDataEvent());
                    }
                } else {
                    showEmptyView();
                }
                pbSectionLoader.setVisibility(View.GONE);
            }

            @Override
            public void onFailure(Call<List<Post>> call, Throwable t) {
                showEmptyView();
                t.printStackTrace();
            }
        });
    }
}

活动代码:

@Subscribe (threadMode = ThreadMode.MAIN)
public void onLoadMainDataEvent(LoadMainDataEvent loadMainDataEvent){
    Toast.makeText(activity, "OK", Toast.LENGTH_SHORT).show();
}

我希望在从服务器获取数据到fragment 时,在activity 页面中运行代码。

我该如何解决?请帮我。谢谢

【问题讨论】:

  • 你在Activity注册EventBus了吗?
  • @KishoreJethava,我该怎么办?你能帮助我吗?请
  • 在片段的onStart() 方法中添加这个 - EventBus.getDefault().register(this);
  • 关注官方documents
  • @GaneshKalal,谢谢我的兄弟。没关系,为我工作

标签: java android android-fragments event-bus


【解决方案1】:

试试这个效果很好

FragmentClass.java

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    if (!EventBus.getDefault().isRegistered(this)) {
        EventBus.getDefault().register(this);
     }
}

@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageBusEvent event) {
}

@Override
public void onDestroy() {
        //unregister event bus
        EventBus.getDefault().unregister(this);
        super.onDestroy();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多