NavigationView SwitchCompat button only works when it is selected

72 views Asked by At

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.

1

There are 1 answers

0
Stanojkovic On BEST ANSWER

Okay, I finally figured out what it was all about. I declared SwitchCompat as CompoundButton which was inside ConstraintLayout, in a separate .xml. I removed ConstraintLayout and switched the layout for the button to MenuItem. In the end, it looks like this:

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
}