How to not save to SharedPreferences if cancel was clicked on a ListPreference

StackOverflow https://stackoverflow.com/questions/22161718

  •  19-10-2022
  •  | 
  •  

I need to make it so that if cancel or back was pushed when a ListPreference was open that, the value is not saved in SharedPreferences and takes no effect on the app. I have everything in my application working and have been searching for some type of solution but could not find it. Thanks! Edit: Is there a way to start the list preference with none of the values selected?

有帮助吗?

解决方案

Alright I was playing around and figured it out. The way I did it was I made a string in the res/values/string.xml and gave it its own id(@+id/none). Then in the res/xml/preferences.xml in the ListPreference info I added android:defaultValue="id/none". Now when I open the list of preferences nothing is selected as default.

其他提示

You can handle cancel and back press event explicitly in your app and do the stuff accordingly.

Back button can be handled in following way:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        // your code
        return true;
    }

    return super.onKeyDown(keyCode, event);
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top