Last active
October 8, 2018 19:54
-
-
Save rjlutz/1338ce84dd97764dda103a7565d6a73c to your computer and use it in GitHub Desktop.
Including a SettingsActivity in your Android Studio Project
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
1 - Use existing Android Studio project or create a new project. If new, start with a Basic Activity so that the Settings pulldown is available under the Options menu. | |
2 - It might be good to test deploy to make sure everyting is working ok. | |
3 - Create a new SettingsActivity. File -> New -> Activity -> SettingsActivity | |
4 - Link the new Activity to the Options menu. Navigate to app -> java -> <<your package>> -> MainActivity.java and add the following to onOptionsItemSelected(): | |
@Override | |
public boolean onOptionsItemSelected(MenuItem item) { | |
// ... | |
int id = item.getItemId(); | |
//noinspection SimplifiableIfStatement | |
if (id == R.id.action_settings) { | |
Intent intent = new Intent(getApplicationContext(), SettingsActivity.class); //*** ADD THESE LINES !! *** | |
startActivity(intent); //*** ---------------- *** | |
return true; | |
} | |
return super.onOptionsItemSelected(item); | |
} | |
5 - Confirm that the Settings Activity is accessible from the Options menu pulldown. | |
6 - In order to access the new preferences, add this onResume to your MainActivity.java: | |
@Override | |
protected void onResume() { | |
super.onResume(); | |
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); | |
for (Map.Entry<String, ?> entry : prefs.getAll().entrySet()) | |
Log.d("SETTINGS", entry.getKey() + ": " + entry.getValue().toString()); | |
Log.d("SETTINGS", "switch = " + prefs.getBoolean("example_switch", false)); | |
} | |
7 - Just as in the for loop in step 6, you can access all of the preferences and use them in your MainActivity! | |
8 - To access a single preference, follow the example in the second log statement. | |
9 - The default SettingsActivity.java may be a bit more complex than what you need. You can pare down the layouts and streamline the templated solution for your app's needs. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment