As mentioned in Part I, calling updateConfiguration with the correct parameters for the locale provides a simple way to switch the language used in an app. Of course, the app should always start with the language last selected by the user and should provide an easy method with which to change the displayed language.
Saving state in an Android app can take many forms. For short term, such as handling orientation changes, using savedInstanceState in onCreate or a Headless Retained Fragment works very well. However these methods are not appropriate for user settings which require a persistent storage that spans the app restarting not just the activity. For this type of storage in Android there is a built-in database, SQLite, the file system, or SharedPreferences, which I ended up selecting since I was going to use a PreferenceFragment for my user settings interface.
To implement a PreferenceFragment create a SettingsActivity which extends AppCompatActivity and include the innerClass – MyPreferenceFragment which extends the PreferenceFragment and loads the xml file that defines the preferences.
public class SettingsActivity extends AppCompatActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); getFragmentManager().beginTransaction().replace( R.id.content_frame, new MyPreferenceFragment()).commit(); }
public static class MyPreferenceFragment extends PreferenceFragment{ @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Define the xml file used for preferences addPreferencesFromResource(R.xml.preferences); } }
The activity_settings.xml file is very simple and is used as the fragment container:
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android= "http://schemas.android.com/apk/res/android" android:id="@+id/content_frame" android:layout_width="match_parent" android:layout_height="match_parent"> </FrameLayout>
The preferences.xml file provides the layout for the PreferenceScreen. The built-in widgets available for the preference screen are: CheckBoxPreference, ListPreference and EditTextPreference. In part III, we’ll add a widget that’s very useful for selecting an item from a list, the SpinnerPreference.