[英]Some problems with SharedPreferences Boolean
我有三个类,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按钮的条件为GONE,因此在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");
遇到此错误boolean levelTwoUnlocked = preferences.getBoolean("f2");
类型SharedPreferences中的方法getBoolean(String,boolean)不适用于参数(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)
从首选项中检索布尔值。
参量
键:要检索的首选项的名称。
defValue:如果此首选项不存在,则返回的值。
退货
返回首选项值(如果存在)或defValue。 如果此名称的首选项不是布尔值,则抛出ClassCastException。
现在你的问题:
显然,您还需要传递一个默认值。
像这样改变你的电话
boolean levelTwoUnlocked = preferences.getBoolean("f2", false); // or true according to your default value
PS:请不要以为我很粗鲁,但是当错误明确指出方法定义不匹配或在任何其他此类情况下,您应该至少查找一次文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.