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