2013-08-23 98 views
3

當我更改一個片段時,我想比較一個片段與當前片段。如果它們是相同的,則不需要替換它們。Android比較兩個片段

我試圖

public void displayFragment(Fragment fragment){ 
    FragmentManager fm = getSupportFragmentManager(); 
    Fragment currentFragment = fm.findFragmentById(R.id.content_frame); 
    if(!currentFragment.equals(fragment)) 
     getSupportFragmentManager().beginTransaction().addToBackStack(null).replace(R.id.content_frame, fragment).commit(); 
} 

,但它不工作,該片段被改變,即使新的一個是相同的

的解決方案? 感謝

編輯

解決辦法:找出片段

public void displayFragment(Fragment fragment){ 
    FragmentManager fm = getSupportFragmentManager(); 
    Fragment currentFragment = fm.findFragmentById(R.id.content_frame); 
    if(!fragment.getClass().toString().equals(currentFragment.getTag())){ 
     getSupportFragmentManager() 
     .beginTransaction() 
     .addToBackStack(null) 
     .replace(R.id.content_frame, fragment, fragment.getClass().toString()) // add and tag the new fragment 
     .commit(); 
    } 
} 
+0

如果是在同一類? – Piyush

回答

6

一種方法是給他們的標籤:

public void displayFragment(Fragment fragment, String tag){ 
    FragmentManager fm = getSupportFragmentManager(); 
    Fragment currentFragment = fm.findFragmentById(R.id.content_frame); 
    if(!tag.equals(currentFragment.getTag()) 
     getSupportFragmentManager() 
     .beginTransaction() 
     .addToBackStack(null) 
     .replace(R.id.content_frame, fragment, tag) // add and tag the new fragment 
     .commit(); 
} 

編輯:替代版本從埃因霍溫「使用classnames作爲標記:

public void displayFragment(Fragment fragment){ 
    FragmentManager fm = getSupportFragmentManager(); 
    Fragment currentFragment = fm.findFragmentById(R.id.content_frame); 
    if(!fragment.getClass().toString().equals(currentFragment.getTag())) 
    { 
     getSupportFragmentManager() 
     .beginTransaction() 
     .addToBackStack(null) 
     .replace(R.id.content_frame, fragment, fragment.getClass().toString()) // add and tag the new fragment 
     .commit(); 
    } 
} 
+1

是的!非常感謝你 !爲了避免每次更改片段時都放置標籤,我修改了代碼 public void displayFragment(Fragment fragment){FragmentManager fm = getSupportFragmentManager();} \t片段currentFragment = fm.findFragmentById(R.id.content_frame); \t如果(!fragment.getClass()。的toString()。等於(currentFragment.getTag())){ \t getSupportFragmentManager() \t .beginTransaction() \t .addToBackStack(空) \t .replace(R。 id.content_frame,fragment,fragment.getClass()。toString())//添加並標記新片段 \t .commit(); \t} \t} – psv

+0

或者你可以使用'instanceof'?把事情簡單化。 –

0

基於@亞歷夫評論,代碼應該是這樣的:

public void displayFragment(Fragment fragment){ 

    FragmentManager fm = getSupportFragmentManager(); 
    Fragment currentFragment = fm.findFragmentById(R.id.content_frame); 

    if(!(fragment instanceof currentFragment)) { 
     getSupportFragmentManager() 
      .beginTransaction() 
      .addToBackStack(null) 
      .replace(R.id.content_frame, fragment, fragment.getClass().toString()) // add and tag the new fragment 
      .commit(); 
    } 
}