Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 在ViewPager中使用EventBus时获取混合数据_Android_Fragment_Greenrobot Eventbus - Fatal编程技术网

Android 在ViewPager中使用EventBus时获取混合数据

Android 在ViewPager中使用EventBus时获取混合数据,android,fragment,greenrobot-eventbus,Android,Fragment,Greenrobot Eventbus,当成功发出http请求时,我使用将结果发布到片段。当存在一个订阅者和一个发布者的关系时,这种方法非常有效 但是,在我的应用程序中,我有一个屏幕,它使用带有选项卡的ViewPager。由于页面非常相似,我使用相同的片段,每个选项卡对应不同的参数来下载数据 该片段大致如下所示: public class MyFragment extends Fragment{ @Override public void onCreate(Bundle savedInstanceState) {

当成功发出http请求时,我使用将结果发布到片段。当存在一个订阅者和一个发布者的关系时,这种方法非常有效

但是,在我的应用程序中,我有一个屏幕,它使用带有选项卡的
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);
    }
}
您可能已经猜到了当接收到数据时会发生什么

由于有许多具有相同签名的订阅者正在等待一个
ServerResponse
,因此响应不会转到相应的选项卡,而是在每个片段中接收并显示相同的响应,并且数据会混合


你知道怎么解决这个问题吗?

嘿!这里也有同样的问题,但我有一个解决办法

问题是,您有许多
片段(来自同一对象的实例),并且所有片段都在侦听同一事件,因此在发布事件时,所有片段都会更新

发布事件时,请尝试发送位置,当实例化
片段时,需要存储页面适配器位置。之后,只需检查事件是否与
片段的位置相同

例如:

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

谢谢,你救了我一天