Custom TextSize of BottomNavigationView support android

前端 未结 8 1286
别跟我提以往
别跟我提以往 2020-12-12 23:53

I am trying to change the textSize of BottomNavigationView from android support library 25.0.0



        
8条回答
  •  -上瘾入骨i
    2020-12-13 00:29

    Another solution is to use Spannable to adjust the size color, font or other a text attributes ....

    private static class MenuSpannable extends MetricAffectingSpan{
            int color = Color.RED;
            int size = 40;
    
            public MenuSpannable() {
                setSelected(false);
            }
    
            @Override
            public void updateMeasureState(TextPaint p) {
                p.setColor(color);
                p.setTextSize(size);
                /* p.setText --- whatever --- */
            }
    
            @Override
            public void updateDrawState(TextPaint tp) {
                tp.setColor(color);
                tp.setTextSize(size);
                /* tp.setText --- whatever --- */
            }
            private void setSelected(boolean selected){
                if(selected){
                    color = Color.RED;
                    size = 40;
                }else{
                    color = Color.BLUE;
                    size = 20;
                }
            }
    }
    

    And then set the span for any menu item...

    @Override
    protected void onCreate(Bundle savedInstanceState) {
            BottomNavigationView mBottomNavigationView = (BottomNavigationView)findViewById(R.id.bottom_menu);
            final Menu menu = mBottomNavigationView.getMenu();
            final Font font = Font.getFromContext(this);
            for(int i = 0; i < menu.size(); i++) {
                SpannableString spannableString = new SpannableString(menu.getItem(i).getTitle());
                spannableString.setSpan(new MenuSpannable(),0,spannableString.length(),0);
                menu.getItem(i).setTitle(spannableString);
            }
    }
    

    In case you want the text to change with the selection state

    mBottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                 Menu menu = mBottomNavigationView.getMenu();
                 for(int i = 0; i < menu.size(); i++) {
                    MenuSpannable menuSpannable = new MenuSpannable();
                    menuSpannable.setSelected(item.getItemId() == menu.getItem(i).getItemId());
                    SpannableString sString = new SpannableString(menu.getItem(i).getTitle());
                    sString.setSpan(menuSpannable,0,sString.length(),0);
                    menu.getItem(i).setTitle(sString);
                    }
                return false;
                }
            });
    

提交回复
热议问题