I want to put a bar in the top of each Bottom Navigation View Item's items when it is selected. As the image below, but i don't find the way to do it.
I dont have any idea how to do it
I want to put a bar in the top of each Bottom Navigation View Item's items when it is selected. As the image below, but i don't find the way to do it.
I dont have any idea how to do it
You can achieve it by adding a view on the bottom navigation, check the code below, you can also use this to add any view on the bottom navigation item, such as Badge, small icon, etc..
Layout xml for the bar
<?xml version="1.0" encoding="utf-8"?>
<View xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="100dp"
android:layout_height="2dp"
android:layout_gravity="center_horizontal"
android:background="@color/red"
android:gravity="center"/>
Controller (show/hide)
class BottomNavigationHelper {
fun showBadge(context: Context, bottomNavigationView: BottomNavigationView, @IdRes itemId: Int) {
removeBadge(bottomNavigationView, itemId)
val itemView = bottomNavigationView.findViewById<BottomNavigationItemView>(itemId)
val badge = LayoutInflater.from(context).inflate(R.layout.layout_red_badge, bottomNavigationView, false)
itemView.addView(badge)
}
fun removeBadge(bottomNavigationView: BottomNavigationView, @IdRes itemId: Int) {
val itemView = bottomNavigationView.findViewById<BottomNavigationItemView>(itemId)
if (itemView.childCount == 3) {
itemView.removeViewAt(2)
}
}
}
sample call
BottomNavigationHelper().showBadge(mContext, bottomNavigationView, R.id.navigation_home)
To fix issue with removing badge with Farouq Afghani's answer.
class BottomNavigationHelper {
companion object {
var previousItemId: Int = 0
}
fun showBadge(
context: Context,
bottomNavigationView: BottomNavigationView,
@IdRes itemId: Int
) {
if (previousItemId != 0) {
removeBadge(bottomNavigationView, previousItemId)
}
previousItemId = itemId
val itemView = bottomNavigationView.findViewById<BottomNavigationItemView>(itemId)
val badge = LayoutInflater.from(context)
.inflate(R.layout.layout_nav_top_line, bottomNavigationView, false)
itemView.addView(badge)
}
fun removeBadge(bottomNavigationView: BottomNavigationView, @IdRes itemId: Int) {
val itemView = bottomNavigationView.findViewById<BottomNavigationItemView>(itemId)
if (itemView.childCount == 3) {
itemView.removeViewAt(2)
}
}
}
As suggested by Payam Kokabi, you could use a selector
to determine the background drawable to show. Something along the following lines should work,
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/bottom_item_selected" android:state_checked="true"/>
<item android:drawable="@drawable/bottom_item" android:state_checked="false"/>
</selector>
P.S - You can set the selector as the item background using,
app:itemBackground="@drawable/bottom_item_selector"