android-fragments popBackStack()无法在偏好片段上运作

xzabzqsa  于 2022-11-14  发布在  Android
关注(0)|答案(1)|浏览(185)

我有一个具有不同PreferenceFragmentsAppCompatActivity。我正在使用addToBackStack()调用将fragments添加到backstack,但在使用popBackStack()检索片段时,activity未显示fragmentUI未更新),但getBackStackEntryCount()popBackStack()调用而减少。可能是什么原因?

public class SettingsActivity extends AppCompatActivity {

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getFragmentManager()
            .beginTransaction()
            .replace(R.id.content_frame_settings, new SettingsPreferenceFragment1())
            .addToBackStack("SettingsPreferenceFragment1")
            .commit();
    }

    @Override
    public void onBackPressed() {
        if ( getFragmentManager().getBackStackEntryCount() > 0){
            getFragmentManager().popBackStack();
        } else {
            super.onBackPressed();
        }
    }

    public static class SettingsPreferenceFragment1 extends PreferenceFragment {
        ...
        ...
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.pref_settings1);
            ...
            ...
        }

        @Override
            OnClick(View view){
                if(view == btnNext){
                    getFragmentManager()
                        .beginTransaction()
                        .replace(R.id.content_frame_settings, new SettingsPreferenceFragment2())
                        .addToBackStack("SettingsPreferenceFragment2")
                        .commit();
                }
            }
    }

    public static class SettingsPreferenceFragment2 extends PreferenceFragment {
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.pref_settings2);
        }
    }
}
fzsnzjdm

fzsnzjdm1#

我认为您使用的是支持片段,如果是这样,那么您需要使用getSupportFragmentManager而不是getFragmentManager

相关问题