Android首选项 - 替换首选项功能

时间:2012-07-21 10:24:38

标签: android android-preferences

我在EditPreference中有一个PreferenceActivity,我有一个变量告诉我是否应该允许用户访问此偏好设置或显示一些警告。

我的问题是我无法找到如何在显示之前取消首选项对话框并显示我的提醒(根据变量)。

我尝试在偏好onClickonTreeClick中返回true / false但是没有做任何事情,对话框仍然会弹出。

在Android 2.1+上。

感谢。

1 个答案:

答案 0 :(得分:2)

处理偏好设置点击的DialogPreference.onClick()protected,因此您无法在自己的PreferenceActivity班级成员中覆盖它。

但是,您可以扩展课程以达到您的需要。以下是一个极简主义的例子:

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();
    }

}

在您的XML文件中:

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

PreferenceActivity

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

作为最后一点,请允许我说,无论何时找不到想要的方法,都要考虑看一下Android类本身的工作方式。大多数时候,他们会给你很好的见解,以实现你想要的。

在这种情况下,它是DialogInterface.onClick()方法,如上所述。所以你知道你需要以某种方式覆盖它来实现它。在这种情况下,解决方案是扩展EditTextPreference类本身。

相关问题