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>
PS - You can set the selector as the item background using,
app:itemBackground="@drawable/bottom_item_selector"
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)
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.