由于某些原因,java共享首选项默认为true
如果没有与当前口袋妖怪名称相同的密钥,我希望我的按钮在一开始就显示“catch”,如果有并且其值为true,则显示“release”。默认情况下,我使用getBoolean发送“false”。但出于某种原因,我在每一个新的口袋妖怪中看到的第一个文本是“发布”。有什么不对劲吗
编辑:我包括整个onCreate方法和按钮的onClick方法以及布局
<Button
安卓:id="@+id/button"
安卓:layout_width="match_parent"
安卓:layout_height="wrap_content"
安卓:text="Catch"
安卓:onClick="toggleCatch"
安卓:visibility="visible" />
SharedPreferences catchStorage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pokemon);
requestQueue = Volley.newRequestQueue(getApplicationContext());
url = getIntent().getStringExtra("url");
nameTextView = findViewById(R.id.pokemon_name);
numberTextView = findViewById(R.id.pokemon_number);
type1TextView = findViewById(R.id.pokemon_type1);
type2TextView = findViewById(R.id.pokemon_type2);
pokemonName = getIntent().getStringExtra("name");
catchStorage = getSharedPreferences("catchStorage", Context.MODE_PRIVATE);
Button catchBut = (Button)findViewById(R.id.button);
if(catchStorage.getBoolean(pokemonName, false)){
catchBut.setText("Release");
}
else {
catchBut.setText("Catch");
}
load();
}
public void toggleCatch(View view) {
Button catched = (Button)view;
SharedPreferences.Editor editor = catchStorage.edit();
if(catchStorage.getBoolean(pokemonName, false)){
editor.putBoolean(pokemonName, false);
editor.commit();
catched.setText("Catch");
}
else {
editor.putBoolean(pokemonName, true);
editor.commit();
catched.setText("Release");
}
}
# 1 楼答案
共享首选项的值将由系统设置默认值(在本例中为false),如果用户从未访问或从未创建该变量,如果您或用户更改了该值,则默认值将被忽略。 见http://developer.android.com/guide/topics/data/data-storage.html#pref
因此,要么在之前访问该值,要么将其设置为某个值
更完整的代码片段可能有助于找到原因