我有一個項目有兩個活動(MainActivity和CustomPreferenceActivity)。我有一些代碼,當一個按鈕被點擊時,它會啓動CustomPreferenceActivity。根據在CustomPreferenceActivity上所做的選擇,TextView的字體顏色將會改變。但是,我不喜歡我的解決方案(綁定到onResume來更新UI)。還有其他建議嗎?提前致謝。更好的方法來處理SharedPreferences變化
MainActivity
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);
}
};
}
CustomPreferencesActivity
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, ""));
}
}
我不明白你的問題反正只是看這對sharedpreferences HTTP:/ /rajeshvijayakumar.blogspot.in/2013/03/shared-preferences-example-in-android.html – Aravin
這並不是非常清楚你實際上想要達到什麼目的。你能否詳細說明你的用例? –
我想知道是否有一個「更清潔」的解決方案,我現在擁有。它確實有效,但我不喜歡我必須重寫MainActivity上的onResume。 – MrAppa