Android toolbar center title and custom font

前端 未结 30 3104
时光说笑
时光说笑 2020-11-22 04:11

I\'m trying to figure out the right way to use a custom font for the toolbar title, and center it in the toolbar (client requirement).

At the moment, i\'m using the

30条回答
  •  眼角桃花
    2020-11-22 04:48

        public class TestActivity extends AppCompatActivity {
        private Toolbar toolbar;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            super.setContentView(R.layout.activity_test);
    
            toolbar = (Toolbar) findViewById(R.id.tool_bar); // Attaching the layout to the toolbar object
            setSupportActionBar(toolbar);
    
            customizeToolbar(toolbar);
        }
    
        public void customizeToolbar(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);
    
                        // Apply custom font using the Calligraphy library
                        Typeface typeface = TypefaceUtils.load(getAssets(), "fonts/myfont-1.otf");
                        textView.setTypeface(typeface);
    
                    } 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);
    
                        // Apply custom font using the Calligraphy library
                        Typeface typeface = TypefaceUtils.load(getAssets(), "fonts/myfont-2.otf");
                        textView.setTypeface(typeface);
                    }
                }
            }
    
            // Restore title and subtitle
            toolbar.setTitle(originalTitle);
            toolbar.setSubtitle(originalSubtitle);
        }
    }
    

提交回复
热议问题