nherrmann
nherrmann

Reputation: 167

Programmatically change AppBar background color in Kotlin

I'm pretty new to Android development and completely new to Kotlin. I have an app with a navigation drawer, and am trying to change the color of the AppBarLayout based on what the user selects from the navigation drawer. I've tried a few different methods, and the closest I've come has been to change the toolbar color instead of the whole AppBar. This might be acceptable, but instead of actually setting it to the color I want, it always changes it to a dark grey.

when (item.itemId) {
    R.id.nav_audit -> {
        txtMain.text = "Audit"
        toolbar.setBackgroundColor(R.color.colorAudit)
        loadAudits()
    }
    R.id.nav_testing -> {
        txtMain.text = "Testing"
        toolbar.setBackgroundColor(R.color.colorTesting)
    }
    R.id.nav_workflow -> {
        txtMain.text = "Workflow"
        toolbar.setBackgroundColor(R.color.colorWorkflow)
    }
    R.id.nav_other -> {
        txtMain.text = "Other"
        toolbar.setBackgroundColor(R.color.colorPrimary)
    }
}

I've also looked at possibly changing the theme, but it looks like it may not be easy to do that after the application has already loaded. Any thoughts are appreciated.

Upvotes: 2

Views: 1159

Answers (1)

Jorge Casariego
Jorge Casariego

Reputation: 22212

Besides changing the color of the Toolbar that you are already doing, one way to change the status bar in Kotlin is like this:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
   (activity as? AppCompatActivity)?.window?.statusBarColor = 
        ContextCompat.getColor(context, R.color. colorTesting)
 }

You could do a method that returns the color depending on itemId

Upvotes: 2

Related Questions