DominikTV DominikTV - 4 months ago 16
Java Question

if() in a Settings Activity

I'm a Android-Beginner and want to make a if-question in my settings/preferences-Activity.

Here is my Preferences.java:

package net.dominik.genpush;

import android.os.Bundle;
import android.preference.PreferenceActivity;

public class Preferences extends PreferenceActivity{

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);
}
}


...and my Prefs.xml:

<?xml version="1.0" encoding="utf-8"?>

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

<CheckBoxPreference
android:key="pushCheckBox"
android:title="@string/pushnachr_headline"
android:summary="@string/pushnachr_explain"
android:defaultValue="true">

</CheckBoxPreference>

</PreferenceScreen>


Now I wanted to make something like

public void onCheckboxPush(View b)
{
if (pushCheckBox.isChecked())
{
//CODE
}
else...


but don't know how I can start the methode when the checkbox changes.
In a other way I could use

android:onClick="MethodeNameHere" in my activity.xml-File. This don't work in my PreferenceActivity class so no message.

Is there a (easy) way to do something like the "onClick" in a similar manner?

Answer

You can set listener for checkbox.

CheckBoxPreference checkBox = (CheckBoxPreference) findPreference("pushCheckBox");
checkBox.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object value) {
                //your code here
                return true;
            }
});

According to documentation return true will update the state of the Preference with the new value.

And simply check inside of listener if checkBox is checked.

Comments