2016-04-26 120 views
0

我有一個NavigationViewer活動,它有3個片段。我希望每當用戶從NavigationViewer滑動菜單項中選擇一項時,應用程序將處理所選類別的新片段對象。操作NavigationViewer菜單項點擊

,比如我有一個NavigationViewer菜單項稱爲「MyFragment」 所以我想在該項目上驗證碼

MyFragment myFragment = new MyFragment(); 
fragmentTransaction.replace(R.id.RR, myFragment , "nav_MyFragment ").commit(); 

但是這會導致一個問題,即如果用戶從菜單中選擇「MyFragment」,而它是活動的[看到用戶]它會創建一個新的對象。 並且我只想在從某個片段到另一個片段進行交易時創建該新對象。

有什麼建議嗎?

編輯:檢索由標籤片段,然後檢查是否isVisble()或者isAdded()給空例外

回答

1

你可以保留一個Fragment變量並在那裏分配你的活動片段,然後檢查getClassName(),如果它是被點擊的變量與你當前正在顯示的變量相同,那麼你不會加載一個新變量。

我打算使用來自this的應用程序,我在github中有這些代碼。

然後在你的活動聲明可變片段是這樣的:

Fragment active; 

在您的onOptionsItemSelected()方法中,你所要做的按項目的檢查。

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    int id = item.getItemId(); 
    //noinspection SimplifiableIfStatement 
    if (id == R.id.nav_item1) { 
     if (active.getClass().getSimpleName().equals("FragmentA")) { 
      // then this fragment is already being shown, therefore do nothing 
     } else { 
      FragmentA fragtoadd = new FragmentA(); 
      getFragmentManager().beginTransaction() 
           .remove(fragtoadd) 
           .commit(); 
      active = fragtoadd; // the magic is here, everytime you add a new fragment, keep the reference to it to know what fragment is being shown 
     } 
     return true; 
    } else if (id == R.id.nav_item2) { 
     // do the same as above but for FragmentB, and so on 
     return true; 
    } 
    // ... check all your items 
    return super.onOptionsItemSelected(item); 
} 

如果你在Github有你的代碼,那麼我可以看看它會更好。 希望它有幫助!

+0

請問您能用代碼解釋更多嗎?我是Android的新手 –

+1

太棒了,這真是一個神奇的解決方案,非常感謝 –

0

u必須片段實例添加到堆棧中

getSupportedFragmentManager.addToBackStack(fragment.gettag)

+0

對不起,可以ü解釋更PLZ –

+0

我編輯我的答案,看看 –

0

我假設你可以檢測到實際的項目點擊,所以我做的是這樣的:

private static final String TAG_FRAGMENT_SOME_NAME = "something"; 

mFragmentManager = getSupportFragmentManager(); // or getFragmentManager() if not using support library 
mFragmentTransaction = mFragmentManager.beginTransaction(); 
Fragment myFragment = mFragmentManager.findFragmentByTag(TAG_FRAGMENT_SOME_NAME); 
if (myFragment == null) { 
    myFragment = MyFragment.newInstance(); 
} 
mFragmentTransaction.replace(R.id.RR, myFragment, TAG_FRAGMENT_SOME_NAME).commit(); 
+0

無法解析法'的newInstance()' 注MyFragment延伸android.app.Fragment –

+0

的newInstance()是你自己寫的方法,至於不使用默認的空構造函數。 [檢查這個答案](http://stackoverflow.com/a/9245510/3764592)的一些優點,如何做到這一點/它的優點。 – CounterFlame

+0

是的,我只是寫了它,但這並沒有解決我的問題,因爲,因爲我想它阻止了'MyFragment'的重新創建,如果[看到用戶],但它也阻止了從另一個片段到'MyFragment'我需要在發生這種情況時重新創建它 –