更新/刷新/在两个片段之间进行通信

时间:2013-10-24 16:20:41

标签: android android-fragments android-viewpager

我正在使用ViewPager,我有三个片段Fragment A, Fragment B and Fragment C,其中Fragment AFragment B要传达Fragment C。我已经实现了通信逻辑,但事情就是这样:当从Fragment C传递数据时,我无法刷新/更新Fragment B的视图。当Fragment AFragment C进行通信时,一切正常:视图根据传递的数据进行更新。

Fragment C这里是MediaPlayer ...播放从Fragment B传来的媒体网址,但布局有变化。有人可以告诉我这里发生了什么。这是我到目前为止所做的事情:

接口

public interface MediaInterface {
    public void onPodCastClick(int position,
            ArrayList<HashMap<String, String>> toPass);
}

在片段A和B中

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    // TODO Auto-generated method stub
    String title = data.get(position).get("Title").toString();
    SM.setCurrentPlayedID(title);
    popPass.onPodCastClick(position, data);
}

@Override
public void onAttach(Activity activity) {
    // TODO Auto-generated method stub
    super.onAttach(activity);
    try{
        popPass = (MediaInterface)getActivity();
    } catch(ClassCastException e){
        Log.i(tag, "Activity " + getActivity().getClass().getSimpleName()
                + " does not implement the MediaInterface");
        e.printStackTrace();
    }
}

其中popPassMediaInterface的实例。

在MainActivity(实施ViewPager的地方)

@Override
public void onPodCastClick(int position,
        ArrayList<HashMap<String, String>> toPass) {
    // TODO Auto-generated method stub
    Bundle element = new Bundle();

    element.putSerializable("toPass", toPass);
    element.putInt("position", position);

    Fragment toGo = new FragmentC();
    toGo.setArguments(element);
    FragmentTransaction transaction = getSupportFragmentManager()
            .beginTransaction();
    transaction.add(toGo, "FragmentC").commit();
    pager.setCurrentItem(FRAGMENT_C);
}

在片段C中

Bundle element = getActivity().getSupportFragmentManager()
                    .findFragmentByTag("FragmentC").getArguments();

根据Bundle中的元素在视图中进行了更改。

请帮我弄清楚发生了什么,以及如何刷新这个片段。

我也确实从android developers documentation看到了这一点......但他们没有提到更新用户界面的方法。

2 个答案:

答案 0 :(得分:1)

ViewPagers自动创建右侧和(如果有)左侧片段实例。在你的情况下; B不会更新C,因为它已经添加,并且不会调用C的onCreate方法。如果你从片段A添加C,将会更新,因为你只有A和B片段,C将被创建。
对于解决方案,如果存在C片段,请不要添加它,获取C片段并更新它(使用find fragmentByTag)。

答案 1 :(得分:1)

如果我理解正确,问题是当片段B可见时,片段C也已由ViewPager创建,以便在页面之间平滑滚动。这意味着即使您使用C onResume更新界面,也会在创建片段B时调用该方法。

要解决此问题,您可以覆盖setUserVisibleHint方法,以了解您的片段何时实际变为活动状态:

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);

    if (isVisibleToUser == true) { 
        /* This means your fragment just became the active one.
           You should call a GUI update function here. */
    }
}

然后你需要有一个检查新数据的功能并相应地更新界面。

相关问题