Gun*_*Fan 15 android android-fragments greenrobot-eventbus
我有一个活动,它的布局包含一个FrameLayout.我使用framelayout作为片段容器.我使用FragmentManager事务替换FrameLayout中的片段.
在其中一个片段的onCreate方法中,我使用EventBus注册片段.
@Override
public void onCreate(){
EventBus.getDefault().register(this);
// other initialization code
}
Run Code Online (Sandbox Code Playgroud)
该片段在其布局中具有GridView.每当点击gridView中的项目时,我都会向EventBus发布一个事件
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.fragment_category, container, false);
gridView = (GridView) rootView.findViewById(R.id.categry_grid_view);
gridAdapter = new CustomGridAdapter(getActivity());
gridView.setAdapter(gridAdapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Category clickedCategory = gridAdapter.getItem(position);
EventBus.getDefault().post(new MyEvent());
}
});
Run Code Online (Sandbox Code Playgroud)
此事件的事件处理程序方法位于同一片段中,即片段具有以下方法
public void onEvent(MyEvent e){
//some code;
}
Run Code Online (Sandbox Code Playgroud)
这可以正常工作,直到应用程序失去焦点并变为非活动状态(由于按下主页按钮或屏幕锁定).当我再次激活应用程序时,不会调用事件的事件处理程序.我可以在LogCat中看到以下语句
com.example.app D/Event? No subscribers registered for event class com.example.app.MyEvent
com.example.app D/Event? No subscribers registered for event class de.greenrobot.event.NoSubscriberEvent
Run Code Online (Sandbox Code Playgroud)
谁能告诉我我在这里做错了什么?
编辑1:
当应用程序因屏幕锁定或按下主页按钮而变为非活动状态时,将调用片段的onStop方法.从EventBus取消注册片段的代码位于onStop方法中.当应用程序再次变为活动状态时,将调用片段的onStart和onResume方法.所以我移动我的代码在onStart方法中使用EventBus注册片段.
@Override
public void onStart(){
super.onStart();
EventBus.getDefault().register(this);
}
Run Code Online (Sandbox Code Playgroud)
我放了一些日志语句来检查当应用程序变为活动状态时是否实际调用了onStart方法.它被称为.当应用程序变为非活动状态然后再次激活时,仍然无法正常工作.
编辑2 我忘了提到包含此片段的活动也订阅了EventBus.使用EventBus注册活动的代码在其onCreate方法中,取消注册活动的代码在其onStop方法中.
包含此片段的活动也订阅了EventBus.使用EventBus注册活动的代码在其onCreate方法中,取消注册活动的代码在其onStop方法中.
当应用程序变为非活动状态时(由于屏幕锁定或按下主页按钮),正在调用包含活动的onStop方法,并且它已从EventBus取消注册.由于某种原因,它含有的片段也未注册(我不知道为什么).使用EventBus重新注册片段不起作用.
我通过移动代码将包含活动注销到其onDestroy方法来解决了这个问题.
我仍然不确定为什么这样做有效,但至少它解决了我当前的问题.如果有人有解释或更好的见解,请评论或发布答案.
| 归档时间: |
|
| 查看次数: |
18857 次 |
| 最近记录: |