Changing item colors individually in BottomNavigationView - android

I am looking for a way to programatically change my item colors in my BottomNavigationView.
I found out how to change icons color, i did it as following :
fun setMenu(selected: Int) {
bottomNavigationMenu?.let {
it.menu.findItem(R.id.bottom_menu_home).icon
.setColorFilter(getMenuColor(R.id.bottom_menu_home, selected), PorterDuff.Mode.SRC_ATOP)
// more items
it.menu.findItem(R.id.bottom_menu_fidelity)?.icon
?.setColorFilter(getMenuColor(R.id.bottom_menu_fidelity, selected), PorterDuff.Mode.SRC_ATOP)
}
}
fun getMenuColor(id: Int, selected: Int): Int {
if (Singletons.restaurant.title.isBlank())
getRestaurant()
else {
if (id == selected) return (Singletons.restaurant.color)
else return ContextCompat.getColor(this, R.color.grey7E)
}
return (0)
}
Now I am looking for how to change the title color.
I am looking for something like
it.menu.findItem(R.id.bottom_menu_home).title // etc
but I can't find a correct function to do it.
Here is my items from main_bottom_menu.xml :
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/bottom_menu_home"
android:enabled="true"
android:icon="#drawable/ic_home"
android:iconTint="#color/cardview_dark_background"
android:title="#string/bottom_menu_home"
android:visible="false"
app:showAsAction="ifRoom" />
<!-- 3 more items -->
<item
android:id="#+id/bottom_menu_profile"
android:enabled="true"
android:icon="#drawable/ic_profile"
android:iconTint="#color/cardview_dark_background"
android:title="#string/bottom_menu_profile"
android:visible="false"
app:showAsAction="ifRoom" />
</menu>
Oddly, the text color is equal to my colorPrimary, so it has to be set somewhere.
The goal is to dynamically set a color (from an API).
Any idea of where was my title color set ?

To set the color of all items, you could simply call setItemTextColor() on your BottomNavigationView instance.
To set them individually, you could use a SpannableString:
val titleSpannable = SpannableString("title")
titleSpannable.setSpan(
ForegroundColorSpan(Color.parseColor("#ffffff")),
0,
titleString.length,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
bottomNavigationView.menu.findItem(R.id.your_item_id).title = titleSpannable

Related

Programmatically added submenu items are not selected after navigation

I have the following main menu drawer, where the "Home button" is static, but the elements under "Read groups" are dynamically added. As you can see, the Home menu is properly checked (selected).
The groups all navigate to the same fragment (GroupsShowFragment), but with different parameters. The problem is, that if I navigate to such a group, the menu item selection is not updated (the Home selection even stays active).
Below the drawer_menu.xml code:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:showIn="navigation_view"
>
<group android:checkableBehavior="single">
<item
android:id="#+id/menu_nav_home"
android:icon="#drawable/ic_action_home"
android:title="Home" />
</group>
<group android:checkableBehavior="single" android:id="#+id/groups_sub_holder">
<item
android:id="#+id/groups_holder"
android:title="Read groups">
<menu>
</menu>
</item>
</group>
<item android:title="Controls">
<menu>
<group android:checkableBehavior="single">
<item
android:id="#+id/menu_nav_group_add"
android:icon="#drawable/ic_action_add_group"
android:title="#string/fragment_title_groups_add" />
<item
android:id="#+id/menu_nav_settings"
android:icon="#drawable/ic_action_settings"
android:title="Settings" />
</group>
</menu>
</item>
</menu>
The code used to dynamicly add the read groups (data is coming from a Room database):
// Add menu source: https://stackoverflow.com/a/31722855/1175881
val navigationView: NavigationView = findViewById <NavigationView> (R.id.nav_view)
val menu: Menu = (navigationView.menu.findItem(R.id.groups_holder)).subMenu
menu.clear()
// adding a section and items into it
val allGroups: List<Groups> = GroupsManager.getAllGroups()
allGroups.forEach{
it.uid?.let { it1 -> menu.add(0, it1, 0, it.name) }
}
And the code which is handling the "navigation":
private fun handleNavigateTrigger(menuId: Int){
when(menuId) {
R.id.menu_nav_home -> {
homeFragment = HomeFragment()
showFragment(homeFragment)
}
R.id.menu_nav_settings -> {
settingsFragment = SettingsFragment()
showFragment(settingsFragment)
}
R.id.menu_nav_group_add -> {
groupsAddFragment = GroupsAddFragment()
showFragment(groupsAddFragment)
}
else -> {
groupsShowFragment = GroupsShowFragment.newInstance(menuId)
showFragment(groupsShowFragment)
val navigationView: NavigationView = findViewById <NavigationView> (R.id.nav_view)
Log.e("handleNavigateTrigger", "setCheckedItem($menuId)")
navigationView.setCheckedItem(menuId)
}
}
_drawerLayout.closeDrawer(GravityCompat.START)
}
private fun showFragment(fragment: androidx.fragment.app.Fragment){
supportFragmentManager
.beginTransaction()
.replace(R.id.frame_layout, fragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.commit()
}
The log does show the correct id's (at least the correct integers) used, so I'm a bit lost here. I've added the group with android:checkableBehavior="single" like this, even as whole menu parent, but to no avail. I'm feeling like I miss one small but very important step, but can't find what that is..
This is a self-answer, but wanted to share the found solution for anybody in the future (can only accept this answer in 2 days, so I'll get back to do that)
I've finally stumbled on this SO answer by Danial B.
Using only the setChecked resulted in a partial (but not sufficient and correctly working) checked menu item. I had to make sure that the menu item was checkable with setCheckable. This resulted in the following code for me:
val navigationView: NavigationView = findViewById <NavigationView> (R.id.nav_view)
val groupItem: MenuItem = navigationView.menu.findItem(menuId)
groupItem.isCheckable = true
groupItem.isChecked = true

Weird in popup menu

I have created a menu icon on action bar. When it is clicked, I expect it will show something like this
But it display on the left hand side instead.
What could be this issue ?
override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) {
inflater!!.inflate(R.menu.fragment_menu, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val id = item.getItemId()
if (id == R.id.more) {
var popup: PopupMenu? = PopupMenu(context!!, view!!)
popup?.menuInflater?.inflate(R.menu.pop_up_menu, popup.menu)
popup?.show()
popup?.setOnMenuItemClickListener({ item: MenuItem? ->
when (item!!.itemId) {
R.id.logOut -> {
}
}
true
})
} else
super.onOptionsItemSelected(item)
return true
}
fragment_menu
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="#+id/more"
android:title="menu"
app:showAsAction="always"
android:icon="#drawable/ic_more"/>
</menu>
pop_up_menu
<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/logOut"
app:showAsAction="always"
android:title="Log Out"
/>
</menu>
The view I passing is this
#Nullable
public View getView() {
return this.mView;
}
You are passing the wrong view as what #CodeRed mentioned.
Replace
var popup: PopupMenu? = PopupMenu(context!!, view!!)
to
val vItem = getActivity().findViewById<View>(R.id.more)
var popup: PopupMenu? = PopupMenu(context!!, vItem)
Menu in ActionBar is populated automatically by system, you don't need to write code to populate it.
To achieve the menu like figure 1, fragment_menu should be like:
<menu>
<item android:title="Search" />
<item android:title="Locate" />
<item android:title="Refresh" />
<item android:title="Help" />
<item android:title="Check for update" />
</menu>
onOptionItemSelected is used to handle when above menu is clicked, not used to show the menu.
popup menu is free position menu like right click menus in windows, not the one you expect in figure 1.

How to change the colour of the navigation drawer item

I want to change my navigation drawer list item's background colour to be changed when i click on it.
Also it should change the text and icon colour of that item as well.
Thanks in advance..
This is quite simple and is similar to changing the background of any view that you use. You can simply create a method and write all the change code into it. Pass the view as a parameter in the method.
Whenever you click on any of the navigation drawer items, pass your view on the method.
For instance, check this method
private boolean viewSelected(View view) {
ViewHolder currentViewHolder = (ViewHolder) view.getTag();
KTextView yourtextView = currentViewHolder.yourtextView;
view.setBackgroundColor(ResourceUtil.getInstance().getColor(R.color.colorSideMenuSelectedBackground));
currentViewHolder.viewSelector.setVisibility(View.VISIBLE);
yourtextView.setTypeface(yourtextView.getContext(), ResourceUtil.getInstance().getString(R.string.yourFontName));
if (lastSelectedView == null) {
lastSelectedView = view;
return true;
}
if (lastSelectedView != view) {
ViewHolder oldViewHolder = (ViewHolder) lastSelectedView.getTag();
oldViewHolder.viewSelector.setVisibility(View.GONE);
lastSelectedView.setBackgroundColor(ResourceUtil.getInstance().getColor(android.R.color.white));
KTextView newTextView = oldViewHolder.yourtextView;
newTextView.setTypeface(yourtextView.getContext(), ResourceUtil.getInstance().getString(R.string.yourfontname));
lastSelectedView = view;
return true;
}
return false;
}
This method will simply change the background, font and color of the views.
Hope this helps!
This can be done using https://developer.android.com/guide/topics/resources/color-list-resource.
Create two drawable files :
1.drawer_background
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="checked_background_color" android:state_checked="true" />
<item android:color="default_background_color" />
</selector>
2.drawer_text_background
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="checked_text_color" android:state_checked="true" />
<item android:color="default_text_color" />
</selector>
And add these two properties to your NavigationView ie
app:itemIconTint="#drawable/drawer_background"
app:itemTextColor="#color/drawer_text_background"
one more if some color is overlapping with some other color
app:itemBackground="#android:color/transparent"
Now, All you have to do is to set an item as checked on Click listener of that item to change background and text color. You can do it programmatically.
I solved it setting this attribute to my NavigationView app:itemBackground="#drawable/drawer_selector"
and my drawer_selector is as below
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="#color/white" />
<item android:state_focused="true" android:drawable="#color/white" />
<item android:state_activated="true" android:drawable="#color/white" />
<item android:drawable="#color/orange" />

Display badge on top of bottom navigation bar's icon

I have implemented the bottom navigation view in my app and I have looked every where to display badges on top of the icons like this
I was wondering whether this is even possible to implement. Any help is appreciated.
Thank you.
If you just want to use a stock BottomNavigationView and no third party lib here's how I've done it:
BottomNavigationMenuView bottomNavigationMenuView =
(BottomNavigationMenuView) navigationView.getChildAt(0);
View v = bottomNavigationMenuView.getChildAt(3);
BottomNavigationItemView itemView = (BottomNavigationItemView) v;
View badge = LayoutInflater.from(this)
.inflate(R.layout.notification_badge, itemView, true);
Then here's the layout file:
<merge xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<TextView
android:id="#+id/notifications.badge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top|center_horizontal"
android:layout_marginLeft="10dp"
android:layout_marginStart="10dp"
android:background="#drawable/notification_badge"
android:gravity="center"
android:padding="3dp"
android:text="9+"
android:textColor="#color/white"
android:textSize="11sp" />
</merge>
Then just find TextView by id and set text.
#drawable/notification_badge is just a circle shape drawable
Adding badges is natively supported now, using the latest material dependency
add this to your build.gradle
implementation 'com.google.android.material:material:1.1.0-alpha09'
in your layout add this
<!-- The rest of your layout here ....-->
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:menu="#menu/bottom_nav_menu"
/>
then you can just
val navBar = findViewById<BottomNavigationView>(R.id.bottom_navigation)
navBar.getOrCreateBadge(R.id.action_add).number = 2
R.id.action_add for you would be the id of the menu item you want to put a badge on. Check it from the menu file you feed to the BottomNavigationView.
Make sure your app theme is in Theme.MaterialComponents
you can check it in styles or manifest.
for this example mine was this
<style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
<item name="android:statusBarColor" tools:targetApi="lollipop">#color/colorPrimary</item>
</style>
Edit 2020:
Use BottomNavigation from material components instead, it gives
support to add badges on items and many other features out of the box:
https://github.com/material-components/material-components-android/blob/master/docs/components/BottomNavigation.md
Old Answer:
When using support library Bottom Navigation bar, its quite complex to show a badge/notification on menu items.
However there are easy solutions to get it done. Such as
https://github.com/aurelhubert/ahbottomnavigation
This library is more advanced version of Bottom Navigation bar. And you can set a badge on menu item simply using this code snippet.
bottomNavigation.setNotification(notification, bottomNavigation.getItemsCount() - 1);
And you'll get following result
EDIT 2:
BottomNavigationView now supports showing badge natively, as said in the doc here.
bottomNavigation.getOrCreateBadge(menuItemId)
I was facing the same issue and I didn't want to use a library.
So I created a custom layout called layout_news_badge:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/badge_frame_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/badge_text_view"
android:layout_width="19dp"
android:layout_height="19dp"
android:textSize="11sp"
android:textColor="#android:color/white"
android:background="#drawable/news_bottom_nav_bg"
android:layout_gravity="top"
android:layout_marginTop="4dp"
android:layout_marginStart="16dp"
android:gravity="center"
android:padding="2dp"
tools:text="9+" />
</FrameLayout>
TextView background(news_bottom_nav_bg):
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
<solid android:color="?attr/colorPrimary" />
</shape>
Then I created a BottomMenuHelper with this 2 methods:
public static void showBadge(Context context, BottomNavigationView
bottomNavigationView, #IdRes int itemId, String value) {
removeBadge(bottomNavigationView, itemId);
BottomNavigationItemView itemView = bottomNavigationView.findViewById(itemId);
View badge = LayoutInflater.from(context).inflate(R.layout.layout_news_badge, bottomNavigationView, false);
TextView text = badge.findViewById(R.id.badge_text_view);
text.setText(value);
itemView.addView(badge);
}
public static void removeBadge(BottomNavigationView bottomNavigationView, #IdRes int itemId) {
BottomNavigationItemView itemView = bottomNavigationView.findViewById(itemId);
if (itemView.getChildCount() == 3) {
itemView.removeViewAt(2);
}
}
Then when I call it in my Activity:
BottomMenuHelper.showBadge(this, mBottomNavigationView, R.id.action_news, "1");
EDIT 1:
Added improvement by suggestion jatin rana
Update: now material support badge, see more below
material baging
bottom navigation
val badge = bottomNavigation.getOrCreateBadge(menuItemId)
badge.isVisible = true
// An icon only badge will be displayed unless a number is set:
badge.number = 99
Old answer
base on #Tinashe's answer, i'd like badge show as bellow without number:
code:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)
// position = 2
addBadge(POSITION_HISTORY)
}
/**
* add badge(notification dot) to bottom bar
* #param position to get badge container
*/
#SuppressLint("PrivateResource")
private fun addBadge(position: Int) {
// get badge container (parent)
val bottomMenu = navigation.getChildAt(0) as? BottomNavigationMenuView
val v = bottomMenu?.getChildAt(position) as? BottomNavigationItemView
// inflate badge from layout
badge = LayoutInflater.from(this)
.inflate(R.layout.badge_layout, bottomMenu, false)
// create badge layout parameter
val badgeLayout: FrameLayout.LayoutParams = FrameLayout.LayoutParams(badge?.layoutParams).apply {
gravity = Gravity.CENTER_HORIZONTAL
topMargin = resources.getDimension(R.dimen.design_bottom_navigation_margin).toInt()
// <dimen name="bagde_left_margin">8dp</dimen>
leftMargin = resources.getDimension(R.dimen.bagde_left_margin).toInt()
}
// add view to bottom bar with layout parameter
v?.addView(badge, badgeLayout)
}
badge_layout.xml (badge_size=12dp)
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="#dimen/badge_size"
android:layout_height="#dimen/badge_size"
android:background="#drawable/new_notification" />
and drawable background new_notification.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<corners android:radius="100dp"/>
<solid android:color="#F44336"/>
</shape>
Badge has now been added as a part of AndroidX BottomNavigationView by BadgeDrawable.
See docs
fun setBadge(count: Int) {
if (count == 0) {
bottomNavigationView.removeBadge(R.id.ticketsNavigation)
} else {
val badge = bottomNavigationView.getOrCreateBadge(R.id.ticketsNavigation) // previously showBadge
badge.number = count
badge.backgroundColor = getColor(R.color.badge)
badge.badgeTextColor = getColor(R.color.blackTextColor)
}
}
// Menu:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/ticketsNavigation"
android:icon="#drawable/vector_drawable_navbar_tickets"
android:title="#string/tickets_title"/>
...
</menu>
Edit:
As noted in the comments it should be possible to just update the badge count without needing to add or remove the badge all the time like this:
fun setBadge(count: Int) {
bottomNavigationView.getBadge(menuItemId)?.isVisible = count > 0
}
As #zxbin answer. you can check BadgeView and try below code
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(this);
navigation.setSelectedItemId(R.id.navigation_store);
BottomNavigationMenuView bottomNavigationMenuView =
(BottomNavigationMenuView) navigation.getChildAt(0);
View v = bottomNavigationMenuView.getChildAt(4); // number of menu from left
new QBadgeView(this).bindTarget(v).setBadgeNumber(5);
source from my gist
A simple way:
As Material Design updated their library and according to
https://medium.com/over-engineering/hands-on-with-material-components-for-android-bottom-navigation-aae2aa9066be
I was able to update (or create my BottomNavigationView Badge) from inside my recycler adapter (in a fragment) without any external lib.
Initial State:
So, as in adapter i got the Context from my activity i access it and recover the instance of bottom navigation:
navBottomView = ((AppCompatActivity)this.context).findViewById(R.id.nav_view);
check if the badge is null (not created yet), if is, set it to quantity choosed:
BadgeDrawable badgeDrawable = navBottomView.getBadge(R.id.navigation_carrinho);
if (badgeDrawable == null)
navBottomView.getOrCreateBadge(R.id.navigation_carrinho).setNumber(item.getQuantidade());
otherwise get the previous quantity and increase the badge value:
int previousValue = badgeDrawable.getNumber();
badgeDrawable.setNumber(previousValue + item.getQuantidade());
Don't forget the imports:
import com.google.android.material.badge.BadgeDrawable;
import com.google.android.material.bottomnavigation.BottomNavigationView;
Final State:
All in One with add to cart button listener:
btnAddCarrinho.setOnClickListener(v -> {
navBottomView = ((AppCompatActivity) this.context).findViewById(R.id.nav_view);
BadgeDrawable badgeDrawable = navBottomView.getBadge(R.id.navigation_carrinho);
if (badgeDrawable == null) {
navBottomView.getOrCreateBadge(R.id.navigation_carrinho).setNumber(item.getQuantidade());
} else {
int previousValue = badgeDrawable.getNumber();
badgeDrawable.setNumber(previousValue + item.getQuantidade());
}
});
Please try this once.
1) Create xml file for badge (ex. notification_badge_view.xml)
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/badge"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_gravity="top|center_horizontal"
android:layout_marginStart="10dp"
android:gravity="center"
android:padding="3dp"
app:srcCompat="#drawable/notification_badge" />
</FrameLayout>
2) Create drawable file for notification dot shape (ex. badge_circle.xml)
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid android:color="#color/colorAccent" />
<stroke
android:width="2dp"
android:color="#android:color/white" />
</shape>
3) In your activity onCreate method add the badge view to BottomNavigationView
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_landing);
addBadgeView();
}
4) And the addBadgeView method is below
private void addBadgeView() {
try {
BottomNavigationMenuView menuView = (BottomNavigationMenuView) bottomNavigationBar.getChildAt(0);
BottomNavigationItemView itemView = (BottomNavigationItemView) menuView.getChildAt(0); //set this to 0, 1, 2, or 3.. accordingly which menu item of the bottom bar you want to show badge
notificationBadge = LayoutInflater.from(LandingActivity.this).inflate(R.layout.view_notification_badge, menuView, false);
itemView.addView(notificationBadge);
notificationBadge.setVisibility(GONE);// initially badge will be invisible
} catch (Exception e) {
e.printStackTrace();
}
}
Note: bottomNavigationBar is your bottom bar view.
5) Refresh badge to show and hide by following method
private void refreshBadgeView() {
try {
boolean badgeIsVisible = notificationBadge.getVisibility() != GONE;
notificationBadge.setVisibility(badgeIsVisible ? GONE : VISIBLE);//makes badge visible and invisible
} catch (Exception e) {
e.printStackTrace();
}
}
6) And finely make hide when we clicking on particular bottom bar page by following line.
bottomNavigationBar.setOnNavigationItemSelectedListener(new
BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem)
{
switch (menuItem.getItemId()) {
case R.id.bottom_bar_one:
//while moving to first fragment
notificationBadge.setVisibility(GONE);
break;
case R.id.bottom_bar_two:
//moving to second fragment
break;
case R.id.bottom_bar_three:
//moving to third fragment
break;
}
return true;
}
});
#Abel's answer is the best unless you already have a complex set of themes and don't have the time to change them all.
However, if a) you are pressed for time and if you are using the Google Material library BottomNavigationView Bar or b) you want to add your own custom view badge - then the accepted answer won't work with com.google.android.material:material:1.1.0
You will need to code for a different view hierarchy than the accepted answer
BottomNavigationItemView itemView = (BottomNavigationItemView) ((BottomNavigationMenuView) mBottomNavigation.getChildAt(0)).getChildAt(2);
View badge = LayoutInflater.from(this).inflate(R.layout.navigation_dot, itemView, false);
itemView.addView(badge);
if you do want to update your theme and update to
com.google.android.material:material:1.1.0-alpha09
then all you need to do instead, is
mBottomNavigation.getOrCreateBadge(R.id.navigation_menu_item_one).setNumber(YOUR_NUMBER);
The remove and number functions are only present in the 1.1.0-alpha09 version (and higher)
You can try this way:
Put a TextView inside the BottomNavigationView for counting (BottomNavigationView is a FrameLayout):
<android.support.design.widget.BottomNavigationView android:id="#id/bottomMenu" style="#style/bottomMenu">
<TextView android:id="#id/bottomMenuSelectionsNumber" style="#style/bottomMenuSelectionsNumber"/>
</android.support.design.widget.BottomNavigationView>
And style them like this:
<style name="bottomMenu">
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">#dimen/toolbarHeight</item>
<item name="android:layout_gravity">center|bottom</item>
<item name="android:background">#color/colorThird</item>
<item name="itemBackground">#drawable/tabs_ripple</item>
<item name="itemIconTint">#drawable/bottom_menu_item_color</item>
<item name="itemTextColor">#drawable/bottom_menu_item_color</item>
<item name="menu">#menu/bottom_menu</item>
</style>
<style name="bottomMenuSelectionsNumber">
<item name="android:text">#string/bottomMenuSelectionsNumber</item>
<item name="android:textSize">#dimen/appSecondFontSize</item>
<item name="android:textColor">#color/white</item>
<item name="android:layout_width">#dimen/bottomMenuSelectionsNumberDim</item>
<item name="android:layout_height">#dimen/bottomMenuSelectionsNumberDim</item>
<item name="android:layout_gravity">right|bottom</item>
<item name="android:layout_marginRight">#dimen/bottomMenuSelectionsNumberMarginR</item>
<item name="android:layout_marginBottom">#dimen/bottomMenuSelectionsNumberMarginB</item>
<item name="android:gravity">center</item>
<item name="android:includeFontPadding">false</item>
<item name="android:background">#drawable/bottom_menu_selections_number_bg</item>
</style>
And bottom_menu_selections_number_bg:
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
<solid android:color="#color/colorAccent"/>
<corners android:radius="#dimen/cornerRadius"/>
</shape>
Have a look in at the documentation page:
https://material.io/develop/android/components/bottom-navigation-view/
TL;DR:
They didn't update the correct methods to use, so they left a small error on the documentation. To add or remove a badge do as follows:
// to remove
bottomNavigationView.removeBadge(R.id.action_settings)
// to add
bottomNavigationView.getOrCreateBadge(R.id.action_settings).apply {
//if you want to change other attributes, like badge color, add a number, maximum number (a plus sign is added, e.g. 99+)
number = 100
maxCharactersCount = 3
backgroundColor = ContextCompat.getColor(context, R.color.color_red)
}
Here's a simple way to create & remove badge count with material bottom navigation.
public class BadgeIconHelper {
public static void showNotificationBadge(BottomNavigationView
bottomNavigationView, #IdRes int itemId, String value) {
BadgeDrawable badge = bottomNavigationView.getOrCreateBadge(itemId);
badge.setBackgroundColor(ContextCompat.getColor(bottomNavigationView.getContext(), R.color.color_primary));
badge.setBadgeTextColor(ContextCompat.getColor(bottomNavigationView.getContext(), R.color.color_white));
badge.setMaxCharacterCount(3);
badge.setVerticalOffset(2);
badge.setVisible(true);
badge.setNumber(Integer.parseInt(value));
}
public static void removeNotificationBadge(BottomNavigationView bottomNavigationView, #IdRes int itemId) {
BadgeDrawable badgeDrawable = bottomNavigationView.getBadge(itemId);
if (badgeDrawable != null) {
badgeDrawable.setVisible(false);
badgeDrawable.clearNumber();
}
}
}
Using support library BottomNavigationView is difficult. An easy solution is using external components.
One easy to handle is: https://github.com/roughike/BottomBar
Checking its documentation it's as easy as:
BottomBarTab nearby = bottomBar.getTabWithId(R.id.tab_nearby);
nearby.setBadgeCount(5);
// Remove the badge when you're done with it.
nearby.removeBadge/();
If you want only dot without number, then simply you can create bottom navigation using com.google.android.material.bottomnavigation.BottomNavigationView
and in java
BottomNavigationView mBtmView = (BottomNavigationView) findViewById(R.id.bottom_navigatin_view);
mBtmView.setOnNavigationItemSelectedListener(this);
mBtmView.getOrCreateBadge(R.id.chatFragment).setBackgroundColor(getResources().getColor(R.color.Red));
i did some changes answer of #ilbose i did in this way and tested small and big screen sizes
../drawable/badge_circle.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
<solid android:color="#color/solid_red_base" />
and ../layout/notifcation_badge.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/badge_frame_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="11dp"
android:layout_gravity="center_horizontal">
<TextView
android:id="#+id/badge_text_view"
android:layout_width="12dp"
android:layout_height="12dp"
android:textSize="11sp"
android:textColor="#android:color/white"
android:background="#drawable/message_badge"
android:layout_gravity="top"
android:layout_centerHorizontal="true"
android:padding="2dp"/> </RelativeLayout>
and in java code
public static void showBadge(Context context, BottomNavigationView
bottomNavigationView, #IdRes int itemId, String value) {
BottomNavigationItemView itemView = bottomNavigationView.findViewById(itemId);
View badge = LayoutInflater.from(context).inflate(R.layout.message_notification_badge, bottomNavigationView, false);
TextView text = badge.findViewById(R.id.badge_text_view);
text.setText(value);
itemView.addView(badge);
}
public static void removeBadge(BottomNavigationView bottomNavigationView, #IdRes int itemId) {
BottomNavigationItemView itemView = bottomNavigationView.findViewById(itemId);
if (itemView.getChildCount() == 4) {
itemView.removeViewAt(4);
}
}
Firstly create a layout file of your badge, then follow these steps
BottomNavigationMenuView menuView = (BottomNavigationMenuView) navigation.getChildAt(0);
BottomNavigationItemView itemView = (BottomNavigationItemView) menuView.getChildAt(2);
View messageBadgeView = LayoutInflater.from(this).inflate(R.layout.message_badge_view, menuView, false);
TextView textView = messageBadgeView.findViewById(R.id.counter_badge);
textView.setText("15");
itemView.addView(messageBadgeView);`

NavigationView menu items with counter on the right

The new NavigationView in the new Design Support Library works really great.
They use "menu-items" to display the options.
But how can I display a counter to the right of the menu item?
Like in this picture:
Or like in the GMail app.
Starting from version 23 of appcompat-v7 NavigationView supports action views, so it is quite easy to implement counter yourself.
Create counter layout, i.e. menu_counter.xml:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:textAppearance="#style/TextAppearance.AppCompat.Body2" />
Reference it in your drawer menu xml, i.e. menu/drawer.xml:
<item
...
app:actionLayout="#layout/menu_counter" />
Note that you should use app namespace, don't try to use android.
Alternatively you can manually set action view with MenuItem.setActionView() method.
Find menu item and set counter:
private void setMenuCounter(#IdRes int itemId, int count) {
TextView view = (TextView) navigationView.getMenu().findItem(itemId).getActionView();
view.setText(count > 0 ? String.valueOf(count) : null);
}
Note, that you will need to use MenuItemCompat if you have to support Android 2.x versions.
My workaround was passing a SpannableString with a different background as new title of the MenuItem.
I known is not the best solution and it's not right-aligned but it works as a counter quite well. Something like this:
NavigationView navigation = (NavigationView)findViewById(R.id.navigation);
Menu menuNav = navigation.getMenu();
MenuItem element = menuNav.findItem(R.id.item5);
String before = element.getTitle().toString();
String counter = Integer.toString(5);
String s = before + " "+counter+" ";
SpannableString sColored = new SpannableString( s );
sColored.setSpan(new BackgroundColorSpan( Color.GRAY ), s.length()-(counter.length()+2), s.length(), 0);
sColored.setSpan(new ForegroundColorSpan( Color.WHITE ), s.length()-(counter.length()+2), s.length(), 0);
element.setTitle(sColored);
To improve the counter, here you can find a good answer to set the corners rounded
Example:
Looking at the source for NavigationView, they currently do not support any custom rendering of the menu items (See NavigationMenuPresenter and NavigationMenuAdapter). Hopefully they expose more functionalities soon as I want to set a custom font on the menu items but am unable to without using reflection.
I wanted to have a badge icon for the counters as well. This badge would be pill shaped and have the ability to be different colors to differentiate between important badges and unimportant badges.
To accomplish this, I created a custom view Badge
class Badge #JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = 0,
defStyleRes: Int = 0
) : LinearLayout(context, attrs, defStyle, defStyleRes) {
private val badgeText: TextView
private var important: Boolean
init {
inflate(context, R.layout.badge, this)
badgeText = findViewById(R.id.badge)
important = false
isImportant(important)
adjustVisibility()
}
fun setText(text: String) {
badgeText.text = text
adjustVisibility()
}
fun isImportant(isImportant: Boolean) {
if (isImportant) {
badgeText.backgroundTintList = ColorStateList.valueOf(
ContextCompat.getColor(
context,
R.color.nav_badge_important
)
)
} else {
badgeText.backgroundTintList = ColorStateList.valueOf(
ContextCompat.getColor(
context,
R.color.nav_badge_unimportant
)
)
}
}
private fun adjustVisibility() {
if (badgeText.text.isNullOrBlank() && this.visibility == VISIBLE) {
this.visibility = INVISIBLE
} else {
this.visibility = VISIBLE
}
}
}
The layout for the Badge
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical">
<TextView
android:id="#+id/badge"
style="#style/BadgeStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
The style for the Badge
<resources>
<style name="BadgeStyle" parent="Widget.AppCompat.TextView">
<item name="android:textSize">10sp</item>
<item name="android:background">#drawable/badge_curved</item>
<item name="android:textColor">#color/white</item>
</style>
</resources>
The drawable for the Badge
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="300dp" />
<padding
android:bottom="2dp"
android:left="8dp"
android:right="8dp"
android:top="2dp" />
</shape>
For each menu item with the ability to show a Badge, you need to add app:actionViewClass="com.example.ui.Badge" to your Navigation Menu.
The Badge class gives you the ability to set the text and importance of the badge programmatically.
private fun setupBadges(navView: NavigationView) {
val badgesItemOne = navView.menu.findItem(R.id.nav_one).actionView as Badge
val badgesItemTwo = navView.menu.findItem(R.id.nav_two).actionView as Badge
val badgesItemThree = navView.menu.findItem(R.id.nav_three).actionView as Badge
badgesItemOne.setText("6+")
badgesItemOne.isImportant(true)
badgesItemTwo.setText("2")
badgesItemThree.setText("99+")
}
Step 1 :Identify the group item and add “app:actionViewClass=android.widget.TextView” as given below:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_recorder"
app:actionViewClass="android.widget.TextView"
android:icon="#drawable/ic_menu_gallery"
android:title="Gallery" />
<item
android:id="#+id/nav_night_section"
app:actionViewClass="android.widget.TextView"
android:icon="#drawable/ic_menu_slideshow"
android:title="Slideshow" />
</group>
Step 2: Declare the Navigation Drawer menu item and initialize the item with the badge value
//Create these objects above OnCreate()of your main activity
TextView recorder,nightSection;
//These lines should be added in the OnCreate() of your main activity
recorder =(TextView) MenuItemCompat.getActionView(navigationView.getMenu().
findItem(R.id.nav_recorder));
recordSection=(TextView) MenuItemCompat.getActionView(navigationView.getMenu().
findItem(R.id.nav_night_section));
//This method will initialize the count value
initializeCountDrawer();
Step 3: initializeCountDrawer() can be called where ever it’s required. It can also be used to update the count or badge value in the navigation drawer menu item.
private void initializeCountDrawer(){
//Gravity property aligns the text
recorder.setGravity(Gravity.CENTER_VERTICAL);
recorder.setTypeface(null, Typeface.BOLD);
recorder.setTextColor(getResources().getColor(R.color.colorAccent));
recorder.setText("99+");
slideshow.setGravity(Gravity.CENTER_VERTICAL);
slideshow.setTypeface(null,Typeface.BOLD);
slideshow.setTextColor(getResources().getColor(R.color.colorAccent));
//count is added
slideshow.setText("7");
}

Categories

Resources