Change the background color of the ActionBar in the code from the navigation list

I want to change the background color of the action bar when the user selects a selection from the navigation list.

Currently, my code looks like this:

@Override public boolean onNavigationItemSelected(int itemPosition, long itemId) { ColorDrawable colorDrawable = new ColorDrawable(); ActionBar actionBar = getActionBar(); if(itemPosition == 0) { colorDrawable.setColor(0xffFEBB31); actionBar.setBackgroundDrawable(colorDrawable); return true; } if(itemPosition == 1) { colorDrawable.setColor(0xff9ACC00); actionBar.setBackgroundDrawable(colorDrawable); return true; } return false; } 

However, the first time I select itemPosition 1 in the navigation list, it changes the color of the ActionBar to white.

enter image description here
The second time I click itemPosition 1 in the navigation list, I have no problem.

enter image description here
Can someone tell me why this is so and how can I solve the problem? Thanks for the help!

+5
source share
3 answers

Try the following:

 myActivity.invalidateOptionsMenu(); 
+6
source

Try using this code:

 ColorDrawable colorDrawable = new ColorDrawable(Color.parseColor("#ffFEBB31")); actionBar.setBackgroundDrawable(colorDrawable); 
+10
source

I had the same problem.

For Xamarin users in Visual Studio, etc.

Paste this right after SetContentView (Resource.Layou ...... into the activity class.

// Setting ActionBar (Toolbar) background color natively var actionBar = this.ActionBar; actionBar.SetBackgroundDrawable(new ColorDrawable(Color.Black));

You can change it as you see fit to do more in the actionBar variable.

Thank you for helping.

0
source

Source: https://habr.com/ru/post/974984/


All Articles