簡體   English   中英

向底部導航視圖項添加頂部欄

[英]Add a top bar to a bottom navigation view item

我想在每個底部導航視圖項目的項目被選中時在它的頂部放置一個欄。 如下圖,但我沒有找到方法。 在此處輸入圖片說明

我不知道該怎么做

如Payam Kokabi所建議,可以使用selector確定要顯示的背景可繪制對象。 遵循以下思路應該可以,

<?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-您可以使用以下方式將選擇器設置為項目背景,

app:itemBackground="@drawable/bottom_item_selector"

您可以通過在底部導航上添加一個視圖來實現它,檢查下面的代碼,也可以使用它在底部導航項上添加任何視圖,例如徽章,小圖標等。

欄的布局 xml

<?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"/>

控制器(顯示/隱藏)

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)
        }
    }
}

樣品電話

BottomNavigationHelper().showBadge(mContext, bottomNavigationView, R.id.navigation_home)

用 Farouq Afghani 的回答解決移除徽章的問題。

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)
    }
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM