Search code examples
javaandroidandroid-preferences

Android: How to enable a setting from a different activity?


I want to toggle a SwitchPreference from another activity (Main Activity).

I have an activity where I ask the user if they want to enable notifications. It contains two buttons and they either click yes or no, as shown below:Picture of yes and no buttons

I want the answer to be saved and the SwitchPreference to either be toggled, On for yes or off for no. (as well as the SwitchPreference state)

I'm really stuck on how to do this.

Any advice or answers would be most appreciated?


Solution

  • You've got a couple options.

    1. You could do as @0X0nosugar suggested where you simply store the new setting value in SharedPreferences and check the value when resuming the previous activity.
    2. You could use startActivityForResult(intent, SOME_CONSTANT_IDENTIFIER) (vs just startActivity(intent)) in order to have your settings activity return a result to your calling activity. The concept here is that you're starting a new activity which will return a result back to the previous activity. You could then check the value, store it where needed, and update any relevant UI items. Here's an article on how this works https://developer.android.com/training/basics/intents/result.