Remove BottomNavigationView labels

前端 未结 8 716
一向
一向 2020-11-27 03:47

Google released new support library v25 with BottomNavigationView

is there any way to remove items labels ?

8条回答
  •  萌比男神i
    2020-11-27 04:38

    I wanted to remove both the shift animation and the labels and none of the solutions here worked well for me, so here's the one I built based on everything I learned here:

    public void removeLabels(@IdRes int... menuItemIds) {
        getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override public boolean onPreDraw() {
                getViewTreeObserver().removeOnPreDrawListener(this);
    
                // this only needs to be calculated once for an unchecked item, it'll be the same value for all items
                ViewGroup uncheckedItem = findFirstUncheckedItem(menuItemIds);
                View icon = uncheckedItem.getChildAt(0);
                int iconTopMargin = ((LayoutParams) uncheckedItem.getChildAt(0).getLayoutParams()).topMargin;
                int desiredTopMargin = (uncheckedItem.getHeight() - uncheckedItem.getChildAt(0).getHeight()) / 2;
                int itemTopPadding = desiredTopMargin - iconTopMargin;
    
                for (int id : menuItemIds) {
                    ViewGroup item = findViewById(id);
                    // remove the label
                    item.removeViewAt(1);
                    // and then center the icon
                    item.setPadding(item.getPaddingLeft(), itemTopPadding, item.getPaddingRight(),
                            item.getPaddingBottom());
                }
    
                return true;
            }
        });
    }
    
    @SuppressLint("RestrictedApi")
    private ViewGroup findFirstUncheckedItem(@IdRes int... menuItemIds) {
        BottomNavigationItemView item = findViewById(menuItemIds[0]);
        int i = 1;
        while (item.getItemData().isChecked()) {
            item = findViewById(menuItemIds[i++]);
        }
        return item;
    }
    

    Just add this method to your custom BottomNavigationView and call it passing the ids of the menu items.

提交回复
热议问题