In my code I have a SwitchCompat
button located in the NavigationView
that should store some values in SharedPreferences
. The button works, but in order for it to work properly, it must first be selected, ie. you must first click on the text of the button and then on the switch itself. I can't find the reason why this is happening. My code looks like this:
**MainActivity.kt**
class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {
... // onCreate(), etc
override fun onNavigationItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.srch_view -> Toast.makeText(applicationContext, "First", Toast.LENGTH_SHORT).show()
R.id.switch_lay -> saveValues()
}
drawer_layout.closeDrawer(GravityCompat.START)
return true
}
...// rest of code
fun saveValues() {
val btn = navView.findViewById<NavigationView>(R.id.navView)
val compoundBtn: SwitchCompat = btn.findViewById(R.id.switch_btn)
prefs = getPreferences(Context.MODE_PRIVATE)
editor = prefs.edit()
mDarkTheme = prefs.getBoolean("isChecked", false)
compoundBtn.setOnCheckedChangeListener { _, isChecked ->
if (isChecked) {
// The toggle is enabled
editor.putBoolean("isChecked", true)
editor.apply()
Log.e("PREFS ", "SAVED ")
} else {
// The toggle is disabled
editor.putBoolean("isChecked", false)
editor.apply()
Log.e("PREFS ", "NOT SAVED ")
}
}
}
...
}
Note: the button works, the only problem is that it must be selected in order to work properly. It would be good if someone could help.
Okay, I finally figured out what it was all about. I declared SwitchCompat as
CompoundButton
which was insideConstraintLayout
, in a separate .xml. I removedConstraintLayout
and switched the layout for the button toMenuItem
. In the end, it looks like this:MainActivity.kt