在SDK <24中删除后,片段仍然存在

时间:2019-05-12 02:21:51

标签: android android-fragments android-fragmentactivity

我正面临在SDK <24中删除Fragment的问题。

removeFragment()

FragmentTransaction frgTrans = fragmentMng.beginTransaction();
MyFragment myFrg = (MyFragment) fragmentMng.findFragmentByTag(TAG_MY_FRAGMENT);
frgTrans.remove(myFrg).commit();

getFragment()

MyFragment myFrg = (MyFragment) fragmentMng.findFragmentByTag(TAG_MY_FRAGMENT);
if (myFrg == null ) {
   // Do sth
}
// But I checked that myFrg is NOT NULL ???

此外,此问题仅在SDK <24(Android 5,6)中发生。
<24和24以上的Android SDK之间有什么区别?
我也尝试调用commitNow()来同步执行,但这是同样的问题。

if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
    frgTrans.commit();
    fragmentMng.popBackStack();
} else {
    frgTrans.commitNow();
}

这里有人遇到同样的问题吗?

更新
我还要检查在添加之前和删除之前获得的片段hashcode。一样,所以我可以确认它已经存在...

05-12 11:34:38.705 3916-3916/myapp.test E/FragmentControllerTest: hashcode before remove: 136290746  
05-12 11:34:39.856 3916-3916/myapp.test E/FragmentControllerTest: hashcode before add: 136290746

更新代码
致电关注:

GotoActivity 1: AddMyFragment()  
GotoActivity 2: (destroy Activity1 ) removeMyFragment()  
BackToActivity1: AddMyFragment() (onResume)

代码:

private void addMyFragment() {
    MyFragment myFrg = (MyFragment) mActivity.getSupportFragmentManager().findFragmentByTag(TAG_MY_FRAGMENT);
    if (myFrg == null) {
        try {
            myFrg = new MyFragment();
            FragmentTransaction frgTrans = mActivity.getSupportFragmentManager().beginTransaction();
            frgTrans.add(R.id.my_fragment, myFrg, TAG_MY_FRAGMENT);
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                frgTrans.commit();
            } else {
                frgTrans.commitNow();
            }
        } catch (Exception e) {}
    } else {
        Log.e(TAG, "hash code after remove: " + myFrg.hashCode());
    }
}  

private void removeMyFragment() {   
    MyFragment myFrg = (MyFragment) mActivity.getSupportFragmentManager().findFragmentByTag(TAG_MY_FRAGMENT);
    if (myFrg != null) {
    Log.e(TAG, "hash code after add: " + myFrg.hashCode());
        try {
            FragmentTransaction frgTrans = mActivity.getSupportFragmentManager().beginTransaction();
            frgTrans.remove(myFrg);
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                frgTrans.commit();
                mActivity.getSupportFragmentManager().popBackStack();
            } else {
                frgTrans.commitNow();
            }

        } catch (Exception e) {}
    }
}

0 个答案:

没有答案