当成功发出http请求时,我正在使用EventBus将结果发布到片段。当有一个订户和一个发布者关系时,这很好用。
但是,在我的应用程序中,我有一个使用ViewPager
带有选项卡的屏幕。并且由于页面非常相似,因此我使用相同的片段,并使用与每个选项卡相对应的不同参数来下载数据。
片段看起来与以下几行相似:
public class MyFragment extends Fragment{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EventBus.getDefault().register(this);
}
public void onEvent(ServerResponse response) {
updateUi(response);
}
@Override
public void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
}
您可能已经猜到接收数据时会发生什么。
由于有许多具有相同签名的订户,等待a ServerResponse
,因此响应不会转到相应的选项卡,但是会在每个片段中接收并显示相同的响应,并且会混合数据。
你有什么想法要解决吗?
嘿!同样的问题在这里,但我有解决方案。
问题是您有很多Fragments
(来自同一对象的实例),并且所有实例都在侦听同一事件,因此发布事件时,所有实例都将更新。
发布事件时,请尝试发送位置,并在实例化时Fragment
需要存储页面适配器位置。之后,只需检查事件是否与您的位置相同即可Fragment
。
例如:
public static QuestionFragment newInstance(int position) {
QuestionFragment fragment = new QuestionFragment();
Bundle args = new Bundle();
args.putInt(ARG_POSITION, position);
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
vMain = inflater.inflate(R.layout.fragment_question, container, false);
EventBus.getDefault().post(new GetQuestionEvent(mPosition));
return vMain;
}
public void onEvent(GetQuestionEvent e) {
if (e.getQuestion().getPosition() == mPosition) {
TextView tvPostion = (TextView) vMain.findViewById(R.id.tv_position);
tvPostion.setText("" + e.getQuestion().getPosition());
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句