【发布时间】:2015-04-28 07:49:46
【问题描述】:
我正在尝试使用shared preferences 检索editText 值和按钮颜色。对于editText,它工作得很好,但问题在于保存和加载按钮的颜色。请注意,我想通过onWriteClick 方法保存按钮的当前颜色,并通过onReadClick 按其颜色为按钮着色。
这是我写的:
Button btn ;
EditText c;
private static final String KEY = "key";
private SharedPreferences preferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
c = (EditText) findViewById(R.id.editText1);
btn = (Button) findViewById(R.id.button);
preferences = getSharedPreferences("preferences", Context.MODE_PRIVATE);
}
//shared preferences
@SuppressLint("NewApi")
public void onWriteClick() {
Editor editor = preferences.edit();
Editor color = preferences.edit();
editor.putString(KEY, c.getText().toString());
//Here is the problem
color.putString(KEY, btn.setBackgroundColor("#FFFFF"));
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD) {
editor.apply();
} else {
// This call is synchronous and should be done in a background
// thread
editor.commit();
}
}
public void onReadClick() {
String text = preferences.getString(KEY, null);
c.setText(text);
}
}
请帮忙
【问题讨论】:
-
您正在使用 KEY 将 EditText 内容和按钮颜色保存在相同的 SharedPreference 位置。定义两个标签:TEXT_KEY、COLOR_KEY 并使用 TEXT_KEY 保存文本,使用 COLOR_KEY 保存颜色