Currently I have created the change language inside the alert dialog with setSingleChoiceItems, setPositiveButton and setNegativeButton. How do I prevent the language change if clicked setNegativeButton?
private fun showChangeLanguageDialog() {
val listItems = arrayOf(getString(R.string.english), getString(R.string.chinese))
val mBuilder = AlertDialog.Builder(this@LoginActivity)
mBuilder.setTitle(getString(R.string.choose_language))
mBuilder.setCancelable(false)
mBuilder.setSingleChoiceItems(listItems, -1) { dialogInterface, i ->
when (i) {
0 -> {
setLocale("en")
}
1 -> {
setLocale("zh")
}
}}.setPositiveButton(getString(R.string.button_ok)) { dialogInterface, i ->
recreate()
dialogInterface.dismiss()
}.setNegativeButton(getString(R.string.button_no)) { dialogInterface, i -> }
val mDialog = mBuilder.create()
mDialog.show()
}
Right now the setPositiveButton is working correctly and I have setCancelable to false, so how do I able to achieve the setNegativeButton? Thanks
You are not performing any action on the negative button click.
Please do as below.
.setNegativeButton(getString(R.string.button_no)) { dialogInterface, i->
dialogInterface.dismiss();
}
This is because you always set the language when selecting each item in the following code:
mBuilder.setSingleChoiceItems(listItems, -1) { dialogInterface, i ->
when (i) {
0 -> {
setLocale("en")
}
1 -> {
setLocale("zh")
}
}}
So, you need to set the locale only when you click the positive button. This can be achieved by using a temporary variable for your locale. Something like this:
private fun showChangeLanguageDialog() {
...
val temporaryLocale = ""
mBuilder.setSingleChoiceItems(listItems, -1) { dialogInterface, i ->
when (i) {
0 -> {
temporaryLocale = "en"
}
1 -> {
temporaryLocale = "zh"
}
}}.setPositiveButton(getString(R.string.button_ok)) { dialogInterface, i ->
setLocale(temporaryLocale)
recreate()
dialogInterface.dismiss()
}.setNegativeButton(getString(R.string.button_no)) { dialogInterface, i -> }
val mDialog = mBuilder.create()
mDialog.show()
}
Note: code not yet tested.