0

Android beginner here, so please bear with me...

I'm using a drawer where the menu items are added dynamically.Currently, this is what my code looks like:

val menu = nav_view.menu
menu.clear()
val selectedCatalogIsEmpty = selectedCatalogs.isEmpty()
for (catalog in catalogs){
    val menuItem = menu.add(R.id.catalog_items, Menu.FIRST + catalog.catalogId, Menu.NONE, catalog.catalogName)
    val switch = Switch(applicationContext)
    menuItem.actionView = switch
    if(selectedCatalogIsEmpty ||
            selectedCatalogs.contains(catalog.catalogId) ) {
        menuItem.isChecked = true
        switch.isChecked = true
        if(selectedCatalogIsEmpty){
            selectedCatalogs.add(catalog.catalogId)
        }
    }

    switch.setOnCheckedChangeListener { _, isChecked -> menuItem.isChecked = isChecked }
}

val menuItemSettings = menu.add(R.id.settings, Menu.NONE+ 5000, Menu.NONE, "Settings" )

Now, what i'd like to do is change the color of the thum when in the selected state. In order to achieve that, I've added the following to the styles.xml file:

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorPrimary</item>
    <item name="colorControlNormal">@color/colorWhite</item>
    <item name="colorControlActivated">@color/colorPrimary</item>
</style>

Unfortunately, I'm still getting the wrong color during runtime. Instead of the blue. I'm getting a greeny thumb:

enter image description here

It's clear that I've completely missed the point...I've run a couple of searches and people suggest using the SwitchCompat instead of the Switch. I've tried doing that, but I must also be missing something because I've ended up seing the text in really small caps (instead of the thumb I get with the Switch view).

Thanks.

Regards, Luis

Luis Abreu
  • 4,008
  • 9
  • 34
  • 63

1 Answers1

0

Ok, so after more than 3 hours, I've finally found my bug: I was using the applicationContext to initialize the Switch and application's theme isn't initialized: it's only used to apply a default theme for the remaining activities. So, updating the Switch instantiation to something like this solves the problem:

val switch = Switch(this@MainActivity) //kotlin ref to my activity
Luis Abreu
  • 4,008
  • 9
  • 34
  • 63