SharedPreferences Boolean 的一些问题

Some problems with SharedPreferences Boolean

我有三个 class, 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");

中遇到了这个错误

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);
} 

但是游戏被强行关闭了,是不是代码放错了class?因为我把上面的代码放在 level1.class 而不是 menu.class

这是 android 文档。

public abstract boolean getBoolean (String key, boolean defValue)

从首选项中检索布尔值。

参数

key:要检索的首选项的名称。

defValue: 如果此首选项不存在,则值为 return。

Returns

Returns 首选项值(如果存在)或 defValue。如果此名称不是布尔值,则抛出 ClassCastException。

现在你的问题:

它明确表示您也需要传递一个默认值。

像这样改变你的电话

boolean levelTwoUnlocked = preferences.getBoolean("f2", false); // or true according to your default value

PS: 请不要认为我很粗鲁,但是当错误清楚地表明方法定义不匹配时,您应该至少查找一次文档或任何其他此类情况。