Here I have an example of the code for showing an app preference. The first code is a class which extends PreferenceFragment and the second is a class which extends PreferenceActivity.
PreferenceScreen xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<EditTextPreference
android:key="my_nickname"
android:title="Enter your nickname"
android:summary="Here you need to enter your nickname if you want to change it">
</EditTextPreference>
<ListPreference
android:key="color_key"
android:title="Favorite color"
android:summary="What is your favorite color to change your color preference"
android:entries="@array/favorite_colors"
android:entryValues="@array/colors_numbers"
android:defaultValue="1"/>
<CheckBoxPreference
android:key="notification_key"
android:title="I want to receive a notification"
android:summary="If you check this you will receive a notification"
android:defaultValue="false"/>
</PreferenceScreen>
Extend PreferenceFragment class:
import android.os.Bundle;
import android.preference.PreferenceFragment;
public class CustomPreferenceWithFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
Extend PreferenceActivity class:
import android.preference.PreferenceActivity;
import android.os.Bundle;
public class CustomActivity extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new CustomPreferenceWithFragment())
.commit();
}
}
QUESTIONS:
Both offer the same methods, more or less, to edit the internal SharedPreferences of the application, loaded from a file with addPreferencesFromResource
I feel like the documentation summarizes best
If your app supports versions of Android older than 3.0 (API level 10 and lower), you must build the activity as an extension of the PreferenceActivity class.
On Android 3.0 and later, you should instead use a traditional Activity that hosts a PreferenceFragment that displays your app settings. However, you can also use PreferenceActivity to create a two-pane layout for large screens when you have multiple groups of settings.
That being said, Android has evolved far beyond 3.0 API, so it's safe to consider PreferenceActivity as deprecated. Even pre-3.0, I believe there is a support library with PreferenceFragment class.
What is a meaning of android.R.id.content
Its the root element of the screen - Android: What is android.R.id.content used for?
why here fragment is not connected with Activity class(extends Activity or AppCompatActivity) instead of PreferenceActivity
Well, PreferenceActivity
does extend the Activity class, so there is no real reason to use that specific one if you only are loading a Fragment