Ran
Ran

Reputation: 4157

Android Preference - replace preference function

I have an EditPreference in a PreferenceActivity and I have a variable that tells me if I should allow the user to access this preference or to show some alert.

My problem is that I couldn't find how to cancel the preference dialog before it's displayed and to show my alert (according to the variable).

I tried to return true/false in the preference onClick or in onTreeClick but that didn't do anything, the dialog still popped.

On Android 2.1+ .

Thanks.

Upvotes: 0

Views: 272

Answers (1)

davidcesarino
davidcesarino

Reputation: 16209

The DialogPreference.onClick(), which handles clicks to the preference itself, is protected, so you can't override it in your own PreferenceActivity class members.

However, you can extend the class to achieve what you need. Below is a very minimalist example:

package com.example.test;

import android.content.Context;
import android.preference.EditTextPreference;
import android.util.AttributeSet;

public class MyEditTextPreference extends EditTextPreference {

    private Runnable alternative = null;

    public MyDatePickerDialog(Context context, 
            AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public MyDatePickerDialog(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyDatePickerDialog(Context context) {
        super(context);
    }

    public void setAlternativeRunnable(Runnable runnable) {
        alternative = runnable;
    }

    // this will probably handle your needs
    @Override
    protected void onClick() {
        if (alternative == null) super.onClick();
        else alternative.run();
    }

}

In your XML file:

<com.example.test.MyEditTextPreference
        android:key="myCustom"
        android:title="Click me!" />

In your PreferenceActivity:

MyEditTextPreference pref = (MyEditTextPreference) this.findPreference("myCustom");
pref.setAlternativeRunnable(new Runnable() {
    @Override
    public void run() {
        Toast.makeText(getApplication(), "Canceled!", Toast.LENGTH_SHORT)
                .show();
    }
});

As a final note, let me say that whenever you can't find a way to do what you want, think about taking a look at how the Android classes themselves work. Most of the times, they will give you good insights to achieve what you want.

In this case, it's the DialogInterface.onClick() method, as described above. So you know you need to override it somehow to achieve that. In this case, the solution is extending the EditTextPreference class itself.

Upvotes: 2

Related Questions