Consider the following activity:
public class SettingsActivity extends PreferenceActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); PreferenceScreen screen =getPreferenceManager().createPreferenceScreen(this); } }
Android Studio shows a warning for the call to getPreferenceManager()
:
'getPreferenceManager()' is deprecated
This inspection reports where deprecated code is used in the specified inspection scope.
However, it does not describe what corrective action I should take to avoid the warning. I can't find any alternative for obtaining a reference to the PreferenceManager
and I see no other way to create a PreferenceScreen
.
My goal is to programatically populate the PreferenceActivity
with preferences and their default values since these are generated at runtime and cannot be included in xml/preferences.xml
.
Although getPreferenceManager()
is deprecated in SettingsActivity
, it is not deprecated in PreferenceFragment
. Therefore, the correct way to create a PreferenceScreen
is as follows:
public class SettingsActivity extends PreferenceActivity {
public static class SettingsFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PreferenceScreen screen =
getPreferenceManager().createPreferenceScreen(getActivity());
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager()
.beginTransaction()
.replace(android.R.id.content, new SettingsFragment())
.commit();
}
}