PreferenceActivity: getFragmentManager() has been deprecated

Viewed 3883

When testing a android.preference.PreferenceActivity, I get the following warning:

warning: [deprecation] getFragmentManager() in Activity has been deprecated

That is how I obtain a handle to the current PreferenceFragment:

FragmentManager fm = this.mActivity.getFragmentManager();
this.currentFragment = (PreferenceFragment) fm.getFragments().get(1);

Using FragmentActivity.getSupportFragmentManager() is obviously not an option.

I've found PreferenceFragmentCompat, which would replace the deprecated PreferenceFragment.

But is there any androidx replacement for the PreferenceActivity?

2 Answers

What I've came up with is an AppCompatActivity, which inflates androidx PreferenceFragment. 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>
**/
public final class PreferenceCompatActivity extends AppCompatActivity {

    /** the class-name of the main {@link androidx.preference.PreferenceFragment} */
    public static final String MAIN_FRAGMENT = "com.acme.fragment.PreferencesFragment";

    /** framework {@link Intent} extra */
    public static final String EXTRA_SHOW_FRAGMENT = ":android:show_fragment";

    /** framework {@link Intent} extra */
    public static final String EXTRA_NO_HEADERS = ":android:no_headers";

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

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String fragmentName = MAIN_FRAGMENT;
        Intent intent = getIntent();
        if (intent.getStringExtra(EXTRA_SHOW_FRAGMENT) != null) {
            fragmentName = intent.getStringExtra(EXTRA_SHOW_FRAGMENT);
        }
        this.switchToFragment(fragmentName, null);
    }

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

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

    ...
}

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

Related