我是 Android 开发的新手。我最近遇到了一个挑战,它基本上是一个 ViewPager,其中包含您可以在其中滑动的一系列图像。一旦找到适合您的图像,您可以单击底部的按钮来存储您的选择并继续进行下一个 Activity (下一个 Activity 有一个后退按钮,允许他们返回并根据需要选择另一张图像).
由于这是一个离线挑战,我选择使用 SharedPreferences 作为存储此选择的方式。
我的问题是,我如何才能存储此信息一次,如果第二次选择相同的图像,则什么也不会发生,但如果选择了新图像,则会覆盖前一个图像。我假设它涉及一个 if...else 语句,但不太确定如何设置它。这是我当前在按钮的 onClick 方法中的代码。
public void thatsMeClick(View view) {
Intent intent = new Intent(MainActivity.this, PhysicalCondition.class);
startActivity(intent);
SharedPreferences sharedPreferences = this.getSharedPreferences("com.tabernaster.challengeone",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("motivator", viewPager.getCurrentItem());
editor.apply();
int myIntValue = sharedPreferences.getInt("motivator", -1);
Log.i("motivator", Integer.toString(myIntValue));
}
最佳答案
您需要 if
语句是正确的。基本上,您将使用您已有的相同 int myIntValue = sharedPreferences.getInt("motivator", -1);
代码检查您的当前值,但是您会将其移至 editor.putInt 之上
代码。像这样:
int myIntValue = sharedPreferences.getInt("motivator", -1);
if(myIntValue != viewPager.getCurrentItem()){
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("motivator", viewPager.getCurrentItem());
editor.apply();
myIntValue = sharedPreferences.getInt("motivator", -1);
}
但是,由于您使用的是相同的 key ,因此这段代码相当多余。 SharedPreferences
将为您处理覆盖。
关于java - SharedPreferences if语句只存储一个选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35582233/