【问题标题】:NavigationView SwitchCompat button only works when it is selectedNavigationView SwitchCompat 按钮仅在选中时有效
【发布时间】:2020-12-15 16:08:06
【问题描述】:

在我的代码中,我有一个位于NavigationView 中的SwitchCompat 按钮,它应该在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 ")
              }
          }
      }
...
}

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

【问题讨论】:

    标签: android kotlin menuitem navigationview switchcompat


    【解决方案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
    }
    

    【讨论】:

      猜你喜欢
      • 2021-03-18
      • 2015-09-13
      • 2015-03-24
      • 2021-05-04
      • 2020-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-09
      相关资源
      最近更新 更多