簡體   English   中英

Android-如何在替換另一個片段之前保存片段的狀態?

[英]Android - How to save state of fragment before replacing with another fragment?

我正在片段“ A”調用中從服務器獲取數據。 當我將“ A”替換為“ B”時,從“ B”返回到“ A”后,每次都會調用片段“ A”,因此每次都會生成HTTPGET。 如何避免這種情況並在活動中重用REORDER_TO_FRONT之類的片段?

我正在使用此代碼替換新片段

FragmentTransaction transaction = getSupportFragmentManager()
                .beginTransaction();
transaction.replace(R.id.rl_fragment_content, newFragment,
                backStackName);
transaction.addToBackStack(backStackName);
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
        transaction.commit();

當我后退時,

  Fragment fragment = null;
        fragment = getSupportFragmentManager().findFragmentByTag(
                    "some_fragment_name");
        FragmentTransaction transaction = getSupportFragmentManager()
                .beginTransaction();

        transaction.replace(R.id.rl_fragment_content, fragment);
        transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
        transaction.addToBackStack("some_fragment_name");
        transaction.commit();

只需使用以下方法阻止片段重新放大視圖,

if (view != null) {
//this will prevent the fragment from re-inflating(when you come back from B) 
            ViewGroup parent = (ViewGroup) view.getParent();
            parent.removeView(view);
        } else {
//inflate the view and do what you done in onCreateView()
        }

有幾種方法可以做到這一點,但是最簡單的方法是在片段上使用添加和隱藏而不是替換。 此代碼(未經測試)將顯示newFragment2並將newFragment1添加到Backstack。 在您的堆棧中,代碼將顯示newFragment1並將所需的內容添加到堆棧中

FragmentTransaction transaction = getSupportFragmentManager()
            .beginTransaction();
transaction.add(R.id.rl_fragment_content, newFragment1,
            backStackName1); //now you have an instance of newFragment1
transaction.add(R.id.rl_fragment_content, newFragment2,
            backStackName2); //now you have an instance of newFragment2
transaction.addToBackStack(backStackName1);
transaction.show(newFragment2);
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
transaction.commit();

然后

Fragment fragment = null;
fragment = getSupportFragmentManager().findFragmentByTag(
            backStackName1);
FragmentTransaction transaction = getSupportFragmentManager()
        .beginTransaction();

transaction.show(fragment)
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
transaction.addToBackStack("whatever_you_want");
transaction.commit();

請注意,這將保留視圖。 如果要在屏幕旋轉之間保持不變,則需要在主機“活動”中實施Bundle。

暫無
暫無

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

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