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.
getSupportFragmentManager
is not an option. – Dying