KaliMa
KaliMa

Reputation: 2060

How can I launch a DialogFragment from clicking a preference item?

In my preferences.xml file I have things like

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
    xmlns:android="http://schemas.android.com/apk/res/android">

    <PreferenceCategory
        android:title = "Random Title"
        android:key = "random_category">

    </PreferenceCategory>
</PreferenceScreen>

And I have a PreferenceFragment:

public class PrefFragment extends PreferenceFragment  {

    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);
    }

}

I want to add an item to the category where if you click on it, it calls SomeFunc() (which launches a DialogFragment and from there I know how to save preference values using a helper I wrote), but I don't know how to include just a regular clickable Preference that triggers this function.

Upvotes: 4

Views: 654

Answers (1)

P.C. Blazkowicz
P.C. Blazkowicz

Reputation: 489

To add on click event

    Preference button = findPreference(preferenceKey);
    button.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            // Do some stuff here
            return true;
        }
    });

It is also worth checking out Android Studio's default preference page (New -> Activity -> Settings Activity) - it's quite neet but not too straightforward.

Upvotes: 5

Related Questions