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