Tom H.
Tom H.

Reputation: 510

How to programatically set BottomNavigationView background colour at run time

I have a BottomNavigationView* tab bar, and I want to set the background colour, however I don't have the colour until runtime. It appears as though setItemBackground requires a resource id.

Is there some way of creating a resource out of a GradientDrawable or something similar, then passing that new resource id?

Alternatively is there some other way of doing this without using XML that I've missed and would allow me to just pass a colour or Drawable?

It seems weird that this is so difficult...

*actually using BottomNavigationViewEx which is an extension of it from here, but it doesn't make much difference to my question: https://github.com/ittianyu/BottomNavigationViewEx

Upvotes: 0

Views: 1431

Answers (3)

mears
mears

Reputation: 501

In your activity you can directly use such as:

bottomNavigationView.setItemBackgroundResource((R.color.colorxyz));

Hope this works for you.

Upvotes: 0

JitterbugChew
JitterbugChew

Reputation: 401

BottomNavigationViewEx inherits from View, which has a setBackground(Drawable drawable) method. Use that if you're trying to set the background. If you want to change the background of the items, you will have to either subclass or create a custom implementation of BottomNavigationViewEx as it doesn't look like it supports dynamically generated resources. But I don't see anything prohibiting such a thing.

Upvotes: 1

Ricardo
Ricardo

Reputation: 9656

I don't know how it is done in BottomNavigationView or even if it is possible(at least I didn't find anything in the docs that point out for an easy solution) but personally, I have also tried AHBottomNavigation and it seems more complete. It also gives you the possibility of achieving what you want with:

bottomNavigation.setDefaultBackgroundColor(Color.parseColor("#FEFEFE"));

Link to git project: HERE

Upvotes: 2

Related Questions