Search code examples
javaandroidstaticlistenerpreferences

Calling a non-static method in an android OnPreferenceClickListener


/**
 * A preference change listener to resynchronize a contact list
 *
 */
private static Preference.OnPreferenceClickListener resynchronizeContactsListener = new Preference.OnPreferenceClickListener() {
    @Override
    public boolean onPreferenceClick(Preference preference) {
        new AlertDialog() {

        }
    }
}

In a code snippet such as the above, I need to call a non-static method, or create an AlertDialog(). Both of which I am having difficulty doing since the listener is a static method.

For example, the AlertDialog.Builder() constructor requires an android context object to be created, but since the method is static there is no context. I considered passing in the context as a parameter, however I am not sure where to do so without damaging the fact that I am overriding a method.

Thanks in advance


Solution

  • You can implement the Preference.OnPreferenceClickListener into your own class statically and initialise it from your activity code when ready. (I am assuming that you need the listener object to be static for some reason, you may do away with that!)

    private static MyPrefListener myPrefListener = null;
    
    private static class MyPrefListener implements Preference.OnPreferenceClickListener {
    
        private Context mContext;
        public MyPrefListener(Context context) {
            this.mContext = context;
        }
    
        @Override
        public boolean onPreferenceClick(Preference preference) {
            //USE mContext as the context object here
            return false;
        }
    }
    

    Then in your Activity code, do this:

    myPrefListener = new MyPrefListener(this);
    

    I hope the structure of the code is clear.