0

在我的代码中,我有一个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 ")
              }
          }
      }
...
}

注意:按钮有效,唯一的问题是必须选择它才能正常工作。如果有人能帮忙就好了。

4

1 回答 1

1

好吧,我终于弄清楚了它的全部内容。我在单独的 .xml 中将SwitchCompat 声明为CompoundButton内部。ConstraintLayout我删除ConstraintLayout并将按钮的布局切换为MenuItem. 最后,它看起来像这样:

MainActivity.kt

...
var mSwitchBtn: CompoundButton
var mSwitchItem: MenuItem
var mNavView: NavigationView

...

mSwitchItem= mNavView.menu.findItem(R.id.switch_theme)
mSwitchBtn= mSwitchItem.actionView as CompoundButton

mToggleAnim.setOnCheckedChangeListener { buttonView, isChecked -> 

// Rest of code
}
于 2020-12-18T19:42:24.507 回答