Android: How to Center title in ToolBar

后端 未结 19 2040
执念已碎
执念已碎 2020-11-27 19:04

I am using ToolBar in my project first time, so i do not know how to customized the toolbar in android. I need to centered title in to the tool bar and how to do that please

19条回答
  •  悲&欢浪女
    2020-11-27 19:31

    public void centerTitleAndSubtitle(Toolbar toolbar){
        // Save current title and subtitle
        final CharSequence originalTitle = toolbar.getTitle();
        final CharSequence originalSubtitle = toolbar.getSubtitle();
    
        // Temporarily modify title and subtitle to help detecting each
        toolbar.setTitle("title");
        toolbar.setSubtitle("subtitle");
    
        for(int i = 0; i < toolbar.getChildCount(); i++){
            View view = toolbar.getChildAt(i);
    
            if(view instanceof TextView){
                TextView textView = (TextView) view;
    
    
                if(textView.getText().equals("title")){
                    // Customize title's TextView
                    Toolbar.LayoutParams params = new Toolbar.LayoutParams(Toolbar.LayoutParams.WRAP_CONTENT, Toolbar.LayoutParams.MATCH_PARENT);
                    params.gravity = Gravity.CENTER_HORIZONTAL;
                    textView.setLayoutParams(params);
    
                } else if(textView.getText().equals("subtitle")){
                    // Customize subtitle's TextView
                    Toolbar.LayoutParams params = new Toolbar.LayoutParams(Toolbar.LayoutParams.WRAP_CONTENT, Toolbar.LayoutParams.MATCH_PARENT);
                    params.gravity = Gravity.CENTER_HORIZONTAL;
                    textView.setLayoutParams(params);
                }
            }
    
            // Restore title and subtitle
            toolbar.setTitle(originalTitle);
            toolbar.setSubtitle(originalSubtitle);
        }
    }
    

    If you also want a custom font, check out my other answer here: https://stackoverflow.com/a/35723158/445548

提交回复
热议问题