When I attempt to follow Android's Developer guides and tutorials for creating a Settings Activity using Preferences, I receive warnings such as:
"The method addPreferencesFromResource(int) from the type PreferenceActivity is deprecated"
for both of these lines in the code:
getPreferenceManager().setSharedPreferencesName(PREFS_NAME);
addPreferencesFromResource(R.xml.default_values);
I know these are just warnings, but I was wondering if they will cause any issues, now or in the future, when I am running the application that I am designing.
public class DefaultValues extends PreferenceActivity {
static final String PREFS_NAME = "defaults";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getPrefs(this);
getPreferenceManager().setSharedPreferencesName(PREFS_NAME);
addPreferencesFromResource(R.xml.default_values);
}
static SharedPreferences getPrefs(Context context) {
PreferenceManager.setDefaultValues(context, PREFS_NAME, MODE_PRIVATE,
R.xml.default_values, false);
return context.getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
}
}
PreferenceActivity()
is deprecated, but PreferenceFragment()
is now as well. PreferenceFragmentCompat()
is now the way to go:
Add dependency
implementation "androidx.preference:preference:1.1.1"
Or in case you are still using the support library:
implementation "com.android.support:preference-v7:28.0.0"
Extend PreferenceFragmentCompat
class MyPreferenceFragment : PreferenceFragmentCompat() {
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
addPreferencesFromResource(R.xml.app_preferences)
}
}
Show your Fragment
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
supportFragmentManager.beginTransaction().replace(android.R.id.content, MyPreferenceFragment()).commit()
}
Specify preferenceTheme
In your AppTheme, add either of the following preference themes, depending of which one you think looks better:
<item name="preferenceTheme">@style/PreferenceThemeOverlay</item>
<item name="preferenceTheme">@style/PreferenceThemeOverlay.v14.Material</item>
As the method is deprecated, it is recommended that you don't use it in your code, as it is entirely possible that it can be removed in future versions of Android. However, I am yet to come across a deprecated method that has actually been removed from Android.
No alternative method is provided in the method's description because the preferred approach (as of API level 11) is to instantiate PreferenceFragment objects to load your preferences from a resource file. See the sample code here: PreferenceActivity
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With