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

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

  •  19-10-2022
  •  | 
  •  

Pergunta

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?

Foi útil?

Solução

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.

Outras dicas

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);
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top