使用SharedPreferences保存和加载Textcolor和TypeFace



我正在进行的应用程序项目充当了一个个人时间表,在这里你可以写下你第二天的时间表,保存它,在创建应用程序时,你最初输入的所有文本都会保留在那里。我最初使用共享首选项实现保存和加载功能,但现在我想在应用程序中添加一个荧光笔选项,将特定editText中的文本更改为粗体和红色。

我尝试过使用一个布尔sharedPref变量来判断EditText的颜色和字体应该是什么,但我确信我编码错了。这是代码:

EditText et0;
Button hb0, b1, b2;
public static final String SHARED_PREFS = "sharedPrefs";
public static final String SIX_AM = "sixAM";
SharedPreferences sharedPreferences;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MediaPlayer saveMP = MediaPlayer.create(this, R.raw.save);
final MediaPlayer aNewDayMP = MediaPlayer.create(this, R.raw.anewday);
// Each declared EditText variable in the code is then assigned an EditText from the xml.
et0 =(EditText)findViewById(R.id.slot0);
b1=(Button)findViewById(R.id.saveButton);
b2=(Button)findViewById(R.id.clearButton);
hB0=(Button)findViewById(R.id.highLighter0);
sharedPreferences = getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

saveMP.start();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(SIX_AM, et0.getText().toString());
editor.commit();
// Declaring a toast for the user to see they have saved their own data.
Toast.makeText(MainActivity.this, "Saved!", Toast.LENGTH_SHORT).show();
}
});
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
aNewDayMP.start();
et0.setText("");
}
});
hB0.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (et0.getCurrentTextColor()==Color.BLACK) {
et0.setTextColor(Color.RED);
et0.setTypeface(null, Typeface.BOLD);
hBB0 = TRUE;
} else {
et0.setTextColor(Color.BLACK);
et0.setTypeface(null, Typeface.NORMAL);
hBB0 = FALSE;
}

}
});
loadData();
}
// The loadData method
public void loadData(){
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
et0.setText(sharedPreferences.getString(SIX_AM, ""));

Please note I am a complete amateur and did my best to parse away lines of code that weren't important to the question. If anyone can help or has a recommendation on a better way to do this, please let me know, cheers.

我怀疑问题在于您初始化sharedPreferences两次,第一次在onCreate((中作为字段(class属性(,第二次在loadData中作为局部变量。我认为,如果删除loadData中的初始化并简单地使用onCreate中初始化的字段,它应该读取存储的值。

相关内容

  • 没有找到相关文章

最新更新