Note that there are some explanatory texts on larger screens.

plurals
  1. POBetter Way To Handle SharedPreferences Changes
    text
    copied!<p>I have a project that has two activities (MainActivity and CustomPreferenceActivity). I have some code that when a button is clicked, it launches the CustomPreferenceActivity. Depending on the choices made on the CustomPreferenceActivity, the font color of a TextView will change. However, I don't like my solution to the problem (tying into the onResume to update the UI). Any other suggestions? Thanks in advance.</p> <p>MainActivity</p> <pre><code>public class MainActivity extends Activity { private int colorResId; private int fontSize; private OnClickListener buttonListener = getButtonListener(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button button = (Button)findViewById(R.id.preferenceButton); button.setOnClickListener(buttonListener); } @Override public void onResume() { super.onResume(); updateUiBasedOnPreferences(); } private void updateUiBasedOnPreferences() { SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this); String colorPreference = pref.getString("colorPreference", "default"); colorResId = convertStringToColorResId(colorPreference); fontSize = pref.getInt("fontSize", 24); TextView textView = (TextView)findViewById(R.id.textView); textView.setTextColor(colorResId); textView.setTextSize(fontSize); } private int convertStringToColorResId(String input) { if (input.equals("GREEN")) return Color.GREEN; else if (input.equals("RED")) return Color.RED; else if (input.equals("BLUE")) return Color.BLUE; else return Color.BLACK; } private OnClickListener getButtonListener() { return new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getApplicationContext(), CustomPreferencesActivity.class); startActivity(intent); } }; } </code></pre> <p>CustomPreferencesActivity</p> <pre><code>public class CustomPreferencesActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); pref.registerOnSharedPreferenceChangeListener(this); } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { Preference pref = findPreference(key); pref.setSummary(sharedPreferences.getString(key, "")); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload