在我的代码中,我有一个SwitchCompat
位于 中的按钮,该按钮NavigationView
应将一些值存储在SharedPreferences
. 该按钮有效,但为了使其正常工作,必须首先选择它,即。您必须首先单击按钮的文本,然后单击开关本身。我找不到发生这种情况的原因。我的代码如下所示:
**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 ")
}
}
}
...
}
注意:按钮有效,唯一的问题是必须选择它才能正常工作。如果有人能帮忙就好了。