我有三个类,menu.class,level1.class,level2.class。
我有以下main.xml
数据
<Button
android:id="@+id/f1"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginRight="10dp"
android:background="@drawable/button1" />
<ImageView
android:id="@+id/f2lock"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:src="@drawable/levellocked" />
<Button
android:id="@+id/f2"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="@drawable/button2"
android:visibility="gone" />
我有以下main.class
数据
f1 =(Button)findViewById(R.id.f1);
f1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v){
Intent i =new Intent(getApplicationContext(), level1.class);
startActivity(i);
}
});
f2=(Button)findViewById(R.id.f2)
f2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v){
Intent i =new Intent(getApplicationContext(), level2.class);
startActivity(i);
}
});
f2按钮的状态已消失,因此在level1.class
中
if(answer.equalsIgnoreCase("8"))
SharedPreferences preferences = getSharedPreferences("preferences", MODE_PRIVATE);
boolean levelTwoUnlocked = preferences.getBoolean("f2");
if(levelTwoUnlocked){
f2.setVisibility(View.VISIBLE);
f2lock.setVisibility(View.GONE);
}
else {
f2.setVisibility(View.GONE);
f2lock.setVisibility(View.VISIBLE);
}
这是F2按钮setVisibility(View.VISIBLE)
但我在 boolean levelTwoUnlocked = preferences.getBoolean("f2");
中收到此错误
The method getBoolean(String, boolean) in the type SharedPreferences is not applicable for the arguments (String)
已更新。
我已经像这样更改了代码
if(answer.equalsIgnoreCase("8"))
SharedPreferences preferences = getSharedPreferences("preferences", MODE_PRIVATE);
boolean levelTwoUnlocked = preferences.getBoolean("f2", false);
if(levelTwoUnlocked){
f2.setVisibility(View.VISIBLE);
f2lock.setVisibility(View.GONE);
}
else {
f2.setVisibility(View.GONE);
f2lock.setVisibility(View.VISIBLE);
}
但是游戏被强制关闭,是否代码放置在错误的类中?因为我把上面的代码放在 level1.class
中不在menu.class
中
最佳答案
这是 Android 文档。
public abstract boolean getBoolean (String key, boolean defValue)
从首选项中检索 boolean 值。
参数
key:要检索的首选项的名称。
defValue:此首选项不存在时返回的值。
返回
返回首选项值(如果存在)或 defValue。如果此名称的首选项不是 boolean 值,则抛出 ClassCastException。
现在你的问题:
它清楚地表明您也需要传递默认值。
像这样改变你的电话
boolean levelTwoUnlocked = preferences.getBoolean("f2", false); // or true according to your default value
PS:请不要认为我很粗鲁,但是当错误明确指出方法定义不匹配或任何其他此类情况时,您应该至少查找一次文档。
关于java - SharedPreferences Boolean 的一些问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31959332/