How to use SharedPreferences in an if statement?

546 views Asked by At

I have been working with preferences and SharedPreferences and I am a beginner. So I have a XML document that has a checkbox preference:

 <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"/>

And I want to write an if() statement to adjust the rotation angle of my object. I know it would probably be better in this situation to use a list preference or another type of preference but I am just trying to understand preferences first. Here is the if statement:

 //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 is my key value public static final String keyRotation = "touch"; and prefs is my SharedPreference variable SharedPreferences prefs;. I was wondering how I could write an if statement so every time the user checks the check box the rotation angle is gl.glRotatef(angle, 0, 3, -3); and every time the user unchecks it, the rotation angle is gl.glRotatef(angle, 0, -3, 0);. Much gratitude for any help given.

1

There are 1 answers

1
user3704147 On

Add android:onClick="FunctionName" inside

<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"/>

in the XML file and add this function in your corresponding activity:

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

What happens is that the function FunctionName is called every time the user click on CheckBoxPreference.