Skip to content Skip to sidebar Skip to footer

Preferenceactivity: Getfragmentmanager() Has Been Deprecated

When testing a android.preference.PreferenceActivity, I get the following warning: warning: [deprecation] getFragmentManager() in Activity has been deprecated That is how I obtai

Solution 1:

The Fragment-related UI classes that ship as part of the device firmware have been deprecated in Android 28. It is recommended to move to the support library classes for Activitys and Fragments.

There are already other posts about this:

Solution 2:

What I've came up with is an AppCompatActivity, which inflates androidxPreferenceFragment. I've kept the previous EXTRA_SHOW_FRAGMENT, so that switching to a specific PreferenceFragment still would work. EXTRA_NO_HEADERS has not yet been considered:

/**
 * Preference {@link AppCompatActivity}.
 * @see <a href="https://developer.android.com/reference/androidx/preference/Preference Fragment">PreferenceFragment</a>
**/publicfinalclassPreferenceCompatActivityextendsAppCompatActivity {

    /** the class-name of the main {@link androidx.preference.PreferenceFragment} */publicstaticfinalStringMAIN_FRAGMENT="com.acme.fragment.PreferencesFragment";

    /** framework {@link Intent} extra */publicstaticfinalStringEXTRA_SHOW_FRAGMENT=":android:show_fragment";

    /** framework {@link Intent} extra */publicstaticfinalStringEXTRA_NO_HEADERS=":android:no_headers";

    /** the currently displayed {@link PreferenceFragment} */private PreferenceFragment currentFragment;

    @OverridepublicvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StringfragmentName= MAIN_FRAGMENT;
        Intentintent= getIntent();
        if (intent.getStringExtra(EXTRA_SHOW_FRAGMENT) != null) {
            fragmentName = intent.getStringExtra(EXTRA_SHOW_FRAGMENT);
        }
        this.switchToFragment(fragmentName, null);
    }

    privatevoidswitchToFragment(String fragmentName, @Nullable Bundle args) {
        PreferenceFragment fragment;
        switch(fragmentName) {
            // case "": {break;}default: {
                fragment = newPreferencesFragment();
            }
        }
        getFragmentManager().beginTransaction().replace(android.R.id.content, fragment).commit();
        this.currentFragment = fragment;
    }

    @VisibleForTesting(otherwise = VisibleForTesting.NONE)public PreferenceFragment getCurrentFragment() {
        returnthis.currentFragment;
    }

    ...
}

Update: Meanwhile there's PreferenceFragmentCompat, which support this by default.

Post a Comment for "Preferenceactivity: Getfragmentmanager() Has Been Deprecated"