NavigationView menu items with counter on the right

前端 未结 5 848
谎友^
谎友^ 2020-11-27 11:36

The new NavigationView in the new Design Support Library works really great.

They use \"menu-items\" to display th

5条回答
  •  萌比男神i
    2020-11-27 12:08

    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

    
    
        
    
    
    

    The style for the Badge

    
        
    
    

    The drawable for the Badge

    
        
        
    
    

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

提交回复
热议问题