Why custom DialogPreference doesnt trigger on onSharedPreferenceChanged listener?

眉间皱痕 提交于 2019-12-06 04:42:38

问题


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

回答1:


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



来源:https://stackoverflow.com/questions/13851554/why-custom-dialogpreference-doesnt-trigger-on-onsharedpreferencechanged-listener

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!