为什么在onShared preferenceChanged自定义监听器对话框preference犯规触发? [英] Why custom DialogPreference doesnt trigger on onSharedPreferenceChanged listener?

查看:228
本文介绍了为什么在onShared preferenceChanged自定义监听器对话框preference犯规触发?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使对话框preference在preferences,其中用户只需点击正面按钮,触发一些动作。 (清除数据库中没有|?是的)

 公共类MyDialog preference扩展对话框preference {

    公共MyDialog preference(上下文的背景下,ATTRS的AttributeSet){
        超(背景下,ATTRS);
        // TODO自动生成构造函数存根
    }

    @覆盖
    保护无效onDialogClosed(布尔positiveResult){
        super.onDialogClosed(positiveResult);
        Log.d(MainActivity.TAG,#onDialogClosed:+ positiveResult);
    }

}
 

我不居然要坚持什么,只是触发onShared preferenceChanged监听器,这样我就可以处理它的活动。但我无法弄清楚如何触发它

// SOLUTION

  @覆盖
保护无效onDialogClosed(布尔positiveResult){
    super.onDialogClosed(positiveResult);
    如果(positiveResult){
        persistBoolean(getPersistedBoolean(真)!);
    }
    Log.d(MainActivity.TAG,#onDialogClosed:+ positiveResult);
}
 

解决方案

onShared preferenceChanged 被调用,因为注册的共享preference ,所以,除非你改变与对话preference你不会得到相关联的密钥 onShared preferenceChanged 回调。

所以,你可以做的是,每次关闭对话框,你可以改变键的值。类似下面

 文本= getPersistedString(1)
如果(text.length()→10)
   文本=1;
persistString(文字+1);
 

请确保您的对话框preference有一个键和android:持续在XML真正

I am trying to make dialog preference in preferences, where user just click positive button to trigger some action. (Clear database? No | Yes)

public class MyDialogPreference extends DialogPreference {

    public MyDialogPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
    }

    @Override
    protected void onDialogClosed(boolean positiveResult) {
        super.onDialogClosed(positiveResult);
        Log.d(MainActivity.TAG, "# onDialogClosed: " + positiveResult);
    }

}

I dont actually want to persist anything, just trigger onSharedPreferenceChanged listener, so I can handle it in the activity. But I cant figure out how to trigger it

//SOLUTION

@Override
protected void onDialogClosed(boolean positiveResult) {
    super.onDialogClosed(positiveResult);
    if(positiveResult) {
        persistBoolean(!getPersistedBoolean(true));
    }
    Log.d(MainActivity.TAG, "# onDialogClosed: " + positiveResult);
}

解决方案

onSharedPreferenceChanged is called because of the inbuilt callback registered on the sharedpreference, so unless you change the key associated with dialogPreference you are not going to get the onSharedPreferenceChanged callback.

So what you could do is everytime dialog is closed, you could change the value in key. Something like below

text = getPersistedString("1")
if(text.length() > 10)
   text = "1";
persistString(text+"1");

Make sure your dialogPreference has a key and android:persistent as true in xml

这篇关于为什么在onShared preferenceChanged自定义监听器对话框preference犯规触发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆