簡體   English   中英

Android,片段層次結構問題

[英]Android,Problems with Fragment hierarchy

我目前有一個片段,里面有一個視圖尋呼機,它的三個子片段中有一個帶有可選擇項目的回收站視圖,當一個項目被選中時,會顯示另一個帶有回收者視圖的片段(這是一個獨立的片段,未在相同的視圖尋呼機)。

我的情況是這樣

我想做的是用F1,1中的F2替換F1。 調用F2.onCreateView()時,出現以下錯誤:

“ java.lang.IllegalStateException:指定的子代已經有一個父代。必須首先在該子代的父代上調用removeView()。”

為了向FragmentPagerAdapter提供FragmentManager,在F1啟動時調用F1.getChildFragmentManger()。

我要執行的“從F1,1中選擇一項時”的步驟是:

1)獲取父片段

2)從父片段獲取FragmentManager

3)用F2替換父片段(F1)。

我懷疑問題出在我試圖更改片段的方式上,我也總是嘗試從F1,1直接從活動中獲取FragmentManager。 我知道,也許這是一個非常糟糕的主意,但我不得不嘗試一些...

這是當您從“回收者”視圖中選擇一個項目時調用的F1,1方法。

@Override
public void navigateToProductListView(Vendor vendor, Category category) {
    Bundle argument = new Bundle();
    argument.putParcelable(Vendor.TAG, vendor);
    argument.putParcelable(Category.TAG, category);

    FragmentManager fragmentManager = getParentFragment().getFragmentManager();

    ProductListFragment productListFragment = (ProductListFragment) fragmentManager.findFragmentByTag(ProductListFragment.TAG);

    if (productListFragment == null) {
        productListFragment = new ProductListFragment();
        Log.i("ProductListFragment", "was null");
    }

    productListFragment.setArguments(argument);
    Transitions.replaceFragment(fragmentManager, productListFragment, ProductListFragment.TAG, true);
}

和F2的onCreateView()引發異常

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View root = inflater.inflate(R.layout.fragment_product_list, container, false);

    mUnbinder = ButterKnife.bind(this, root);

    ListHelper.init(getActivity(), mRecyclerView);

    Log.i("ProductListFragment","onCreateView()");

    return root;
}

這是我的Transitions類的代碼,我僅使用一個活動,因此用於保存片段的FrameLayout始終相同

public static void replaceFragment(FragmentManager fragmentManager, Fragment fragment, String tag, boolean addToBackStack) {
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
        Slide enterTransition = new Slide(Gravity.BOTTOM);
        enterTransition.setDuration(500);
        fragment.setEnterTransition(enterTransition);
        fragment.setAllowEnterTransitionOverlap(false);
    }

    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.fragment_container, fragment, tag);
    if (addToBackStack) {
        fragmentTransaction.addToBackStack(null);
    }
    fragmentTransaction.commit();
}

FragmentManager fragmentManager = getParentFragment().getFragmentManager(); 此語句為您提供父級專用FragmentManager,用於在此Fragment中放置和管理Fragment。 試試這個FragmentManager fragmentManager = getParentFragment().getActivity().getFragmentManager();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM