【面试】Fragment嵌套Fragment的bug

①Fragment寄身于Activity的layout当中,若想在Fragment的UI中嵌套子Fragment,那么子Fragment的layout必须在嵌套操作中动态添加。否则可能在运行时报异常Caused by: java.lang.IllegalArgumentException: Binary XML file line #25: Duplicate id 0x7f070193, tag null, or parent id 0x0 with another fragment for xxxx

private static View view;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    if (view != null) {
        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null)
            parent.removeView(view);
    }
    try {
        view = inflater.inflate(R.layout.map, container, false);
    } catch (InflateException e) {
        /* map is already there, just return view as it is */
    }
    return view;
}
②出现多个Fragment重复或者覆盖的现象,这是因为Activity被更新的缘故(屏幕旋转),Fragment随之重新启动切初始化新的Fragment。可以选择在onCreat()中saveInstaceState,存储Activity之前更新的状态。
if(savedInstanceState == null)  
{  
    mFOne = new FragmentOne();  
    FragmentManager fm = getFragmentManager();  
    FragmentTransaction tx = fm.beginTransaction();  
    tx.add(R.id.id_content, mFOne, "ONE");  
    tx.commit();  
}
③嵌套子Fragment需要通过ChildFragmentManager进行一个管理。子Fragment与父Fragment共同指向同一个Activity,子Fragment在detached之后会被reset掉,此时容易出现java.lang.IllegalStateException: No activity。因为除了子Fragment被reset意外ChildFragemtManager也需要被reset才行。
@Override
  public void onDetach() {
    super.onDetach();
    try {
      Field childFragmentManager = Fragment.class
          .getDeclaredField("mChildFragmentManager");
      childFragmentManager.setAccessible(true);
      childFragmentManager.set(this, null);

    } catch (NoSuchFieldException e) {
      throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
      throw new RuntimeException(e);
    }
  }
④这是比较奇怪的问题,因为子Fragment的onActivityResult()所需要接收的内容在getAcivity.startActivityForResult之后被Activity拿走了,在getParentFragment.startActivityForResult之后被父Fragment拿走了。咋整,也只能通过在子Fragment定义更新UI的方法求助父Fragment帮忙调用更新了。
protected void onActivityResult(int requestCode, int resultCode, Intent data)
  {
    this.mFragments.noteStateNotSaved();
    int index = requestCode >> 16;
    if (index != 0) {
      index--;
      if ((this.mFragments.mActive == null) || (index < 0) || (index >= this.mFragments.mActive.size())) {
        Log.w("FragmentActivity", "Activity result fragment index out of range: 0x" + Integer.toHexString(requestCode));

        return;
      }
      Fragment frag = (Fragment)this.mFragments.mActive.get(index);
      if (frag == null) {
        Log.w("FragmentActivity", "Activity result no fragment exists for index: 0x" + Integer.toHexString(requestCode));
      }
      else {
        frag.onActivityResult(requestCode & 0xFFFF, resultCode, data);
      }
      return;
    }

    super.onActivityResult(requestCode, resultCode, data);
  }
最后埋单①②参考原文③④参考原文


posted @ 2015-11-26 23:16  gzejia  阅读(475)  评论(0编辑  收藏  举报