8

当我更改片段时,我想将新片段与当前片段进行比较。如果它们相同,则无需更换它们。

我试过

 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();
    }
}
4

3 回答 3

9

识别片段的一种方法是给它们标签:

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();
}

编辑:psv评论的替代版本,使用类名作为标签:

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(); 
    }
} 
于 2013-08-23T15:48:42.353 回答
0

在 Kotlin 中工作的简单代码。这里 Fragment_Current() 是当前片段。

 fun displayFragment(fm: Fragment) {
    if(fm !is Fragment_Current){
        supportFragmentManager.beginTransaction().replace(R.id.ContentFragmentRoot, fm).commit()
    }
}
于 2021-12-07T15:48:49.983 回答
-2

根据@alex-fu 评论,代码应该是这样的:

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(); 
    }
} 
于 2015-04-16T11:36:48.703 回答