我在共享首选项中获取保存的值,但无法根据共享首选项中的值更新TextView或ImageView。
以下是我的共享Pref课程的代码:
public class SharedPref {
public SharedPref(Context context){
}
public void saveString(Context context,String key, String value) {
SharedPreferences sharedPref = context.getSharedPreferences(key,Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(key, value);
editor.apply();
}
public String getString(Context context,String key){
SharedPreferences sharedPref = context.getSharedPreferences(key, Context.MODE_PRIVATE);
String value = sharedPref.getString(key, "");
return value;
}
}
以下是保存的代码&检索首选项值:
@Override
public void onNumberOfOversClick(String _overs) {
final SharedPref sharedPref = new SharedPref(MainActivity.this);
String local = sharedPref.getString(MainActivity.this,"overs");
// custom dialog
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.custom_overs_dialog);
dialog.setTitle("Choose Overs...");
TextView text_3 = (TextView) dialog.findViewById(R.id.text_3);
TextView text_5 = (TextView) dialog.findViewById(R.id.text_5);
final ImageView icon_tick_3 = (ImageView) dialog.findViewById(R.id.icon_tick_3);
final ImageView icon_tick_5 = (ImageView) dialog.findViewById(R.id.icon_tick_5);
if(local == "3" || local == "")
{
icon_tick_3.setImageResource(R.drawable.tick);
}
else if(local == "5")
{
icon_tick_5.setImageResource(R.drawable.tick);
}
dialog.show();
text_3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
icon_tick_3.setVisibility(View.VISIBLE);
icon_tick_3.setImageResource(R.drawable.tick);
icon_tick_5.setVisibility(View.INVISIBLE);
sharedPref.saveString(MainActivity.this, "overs", "3");
}
});
text_5.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
icon_tick_3.setVisibility(View.INVISIBLE);
icon_tick_5.setVisibility(View.VISIBLE);
icon_tick_5.setImageResource(R.drawable.tick);
sharedPref.saveString(MainActivity.this, "overs", "5");
}
});
}
正如您所看到的,我能够在String变量local中检索值,但是当我重新打开应用程序时,ImageView不会更新为R.drawable.tick。
答案 0 :(得分:0)
字符串比较您现在的工作方式。您需要将equals语句更改为此
if(local.equals("3") || local.equals(""))
{
icon_tick_3.setImageResource(R.drawable.tick);
}
答案 1 :(得分:0)
对于字符串比较,您必须使用equals()
方法而不是==
。
所以请将您的代码更新为:
if (local.equals("3") || TextUtils.isEmpty(local)) { ...