Programming Tips - Android: How to make an activity for users to change settings? (PreferenceActivity)

Date: 2018aug13 OS: Android Language: Java/xml Q. Android: How to make an activity for users to change settings? (PreferenceActivity) A. In Android Studio there is a Wizard, use it. If you're using Eclipse... Make a folder called "xml" In xml, make user_settings.xml with:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" > <PreferenceCategory android:title="Category One" > <EditTextPreference android:key="prefName" android:title="Name" android:summary="What is your name" /> </PreferenceCategory> <PreferenceCategory android:title="Category Two" > <CheckBoxPreference android:key="prefSwim" android:defaultValue="false" android:title="Swimming" > android:summary="Do you like swimming" /> <ListPreference android:key="prefDayOfWeek" android:title="Day of Week" android:summary="Select a Day" android:entries="@array/dayEntries" android:entryValues="@array/dayValues" /> </PreferenceCategory> </PreferenceScreen>
Since this uses some arrays in values/array.xml add:
<resources> <string-array name="dayEntries"> <item name="0">Sunday</item> <item name="1">Monday</item> <item name="2">Tuesday</item> <item name="3">Wednesday</item> <item name="4">Thursday</item> <item name="5">Friday</item> <item name="6">Saturday</item> </string-array> <string-array name="dayValues"> <item name="0">sun</item> <item name="1">mon</item> <item name="2">tue</item> <item name="3">wed</item> <item name="4">thu</item> <item name="5">fri/item> <item name="6">sat</item> </string-array> </resources>
Make a Java class called UserSettingsActivity with:
import android.os.Bundle; import android.preference.PreferenceActivity; public class UserSettingsActivity extends PreferenceActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.user_settings); } }
Add it to your manifest:
<application> ... <activity android:name=".UserSettingsActivity"/> ... </application>
Start the activity from your main actiity with:
Intent intent = new Intent(getApplicationContext(), UserSettingsActivity.class); startActivity(intent);
Use SharedPreferences to get settings elsewhere in your app http://google.com/search?q=SharedPreferences You can customize CheckboxPreference, EditTextPreference, ListPreference but that's beyond the scope of this article.