0

我一直在使用首选项和SharedPreferences,我是初学者。所以我有一个都有一个复选框偏好XML文档:如何在if语句中使用SharedPreferences?

<CheckBoxPreference 
     android:key="@string/touch" 
     android:title="@string/adjust_rotation_speed" 
     android:summary="Check if you want to adjust the rotation speed" 
     android:defaultValue="false"/> 

我想写一个if()语句来调整自己的对象的旋转角度。我知道在这种情况下使用列表首选项或其他类型的首选项可能会更好,但我只是首先尝试了解首选项。下面是if语句:

//Draw Bottom Prism 
gl.glPushMatrix(); 
gl.glScalef(0.3f, 0.3f, 0.3f); 
gl.glTranslatef(0f, -8f, 0.2f); 
if(prefs.getBoolean(keyRotation, false)) { 
    gl.glRotatef(angle, 0, 3, -3); 
}else { 
    gl.glRotatef(angle, 0, -3, 0); 
} 
triangle.draw(gl); 
gl.glPopMatrix(); 

keyRotation是我的键值public static final String keyRotation = "touch"; 和首选项是我SharedPreference变量SharedPreferences prefs;。我想知道如何编写if语句,因此每次用户选中复选框时旋转角度为gl.glRotatef(angle, 0, 3, -3);,并且每次用户取消选中时,旋转角度为gl.glRotatef(angle, 0, -3, 0);。非常感谢任何帮助。

回答

0

<CheckBoxPreference 
    android:key="@string/touch" 
    android:onClick="FunctionName" 
    android:title="@string/adjust_rotation_speed" 
    android:summary="Check if you want to adjust the rotation speed" 
    android:defaultValue="false"/> 

在XML文件中添加android:onClick="FunctionName"并在相应的活动添加此功能:

public void FunctionName(View v) 
{ 
    if(prefs.getBoolean(keyRotation, false)) { 
     gl.glRotatef(angle, 0, 3, -3); 
    } 
    else { 
     gl.glRotatef(angle, 0, -3, 0); 
    } 
} 

什么情况是,该功能FunctionName被称为上CheckBoxPreference用户点击每一次。

+0

谢谢你的帮助,但我仍然取得了同样的结果。 – Dashboarrd