Android toolbar center title and custom font

前端 未结 30 2721
时光说笑
时光说笑 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 05:13

    private void makeTitleCenter(String title, Toolbar toolbar) {
        if (title != null && !TextUtils.isEmpty(title.trim())) {
            final String tag = " ";
            if (getSupportActionBar() != null) {
                getSupportActionBar().setTitle(tag);
            }
            TextView titleTv = null;
            View leftBtn = null;
            for (int i = 0; i < toolbar.getChildCount(); i++) {
                View view = toolbar.getChildAt(i);
                CharSequence text = null;
                if (view instanceof TextView && (text = ((TextView) view).getText()) != null && text.equals(tag)) {
                    titleTv = (TextView) view;
                } else if (view instanceof ImageButton) {
                    leftBtn = view;
                }
            }
            if (titleTv != null) {
                final TextView fTitleTv = titleTv;
                final View fLeftBtn = leftBtn;
                fTitleTv.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        fTitleTv.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                        int leftWidgetWidth = fLeftBtn != null ? fLeftBtn.getWidth() : 0;
                        fTitleTv.setPadding(DimenUtil.getResources().getDisplayMetrics().widthPixels / 2 - leftWidgetWidth - fTitleTv.getWidth() / 2, 0, 0, 0);
                        fTitleTv.requestLayout();
                    }
                });
            }
        }
    }
    

提交回复
热议问题