2017-11-26 8 views
1

ナビゲーションアイテムごとに異なるフラグメントを持つアンドロイドナビゲーションドロワーを使用する必要がありますが、問題は次のとおりです。ナビゲーション・ドロワーで再利用フラグメントがすでにインスタンス化されていますか?

*ナビゲーションアイテムに触れたときにフラグメントのインスタンスを保持して再利用する方法。

*もう一度インスタンス化する必要はありません。何度も何度も繰り返しますが、ユーザーの多くの時間がかかります。

誰でも助けてくれますか?ここ

は、私のコードの一部です:

public void selectDrawerItem(MenuItem menuItem) { 
    // Create a new fragment and specify the fragment to show based on nav item clicked 
    Fragment fragment = null; 
    Class fragmentClass; 
    switch(menuItem.getItemId()) { 
     case R.id.nav_inicio: 
      fragmentClass = DestaquesFragment.class; 
      break; 
     case R.id.nav_cardapio: 
      fragmentClass = CategoriasFragment.class; 
      break; 
     case R.id.nav_meusPedidos: 
      fragmentClass = MeusPedidosFragment.class; 
      break; 
     default: 
      fragmentClass = DestaquesFragment.class; 
    } 

    try { 
     fragment = (Fragment) fragmentClass.newInstance(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

    // Insert the fragment by replacing any existing fragment 
    FragmentManager fragmentManager = getSupportFragmentManager(); 
    fragmentManager.beginTransaction().replace(R.id.contentCompartilhado, fragment).commit(); 

    // Highlight the selected item has been done by NavigationView 
    menuItem.setChecked(true); 
    // Set action bar title 
    setTitle(menuItem.getTitle()); 
    // Close the navigation drawer 
    drawer.closeDrawers(); 
} 

答えて

0

あなたのフラグメントを交換したときのことを再利用するために、後でそれを取得するためにそれのためのタグ名を設定します。

getFragmentManager().beginTransaction().replace(R.id.fragmentContentPlaceHolder,yourFragment,"yourFragment").addToBackStack("yourFragment").commitAllowingStateLoss(); 

は今、私たちは

YourFragment yourFragment= (YourFragment)getFragmentManager().findFragmentByTag("yourFragment"); 

すべて完了幸運タグ名によってそれを見つけることを試みることを再利用するためのの名前yourFragment

とスタック内の断片を持っています!

+0

ありがとうございました! –

+0

私はこれを試してみるつもりです。 –

+0

@CharlesCampistaあなたの歓迎、私の答えが受け入れられるならそれを受け入れてください。幸運。 –

関連する問題