Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 627
KaliMa Avatar asked Oct 22 '25 07:10

KaliMa


1 Answers

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.

like image 87
P.C. Blazkowicz Avatar answered Oct 24 '25 20:10

P.C. Blazkowicz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!