Android toolbar center title and custom font

前端 未结 30 3027
时光说笑
时光说笑 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:46

    I use this solution:

    static void centerToolbarTitle(@NonNull final Toolbar toolbar) {
        final CharSequence title = toolbar.getTitle();
        final ArrayList outViews = new ArrayList<>(1);
        toolbar.findViewsWithText(outViews, title, View.FIND_VIEWS_WITH_TEXT);
        if (!outViews.isEmpty()) {
            final TextView titleView = (TextView) outViews.get(0);
            titleView.setGravity(Gravity.CENTER);
            final Toolbar.LayoutParams layoutParams = (Toolbar.LayoutParams) titleView.getLayoutParams();
            layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
            toolbar.requestLayout();
            //also you can use titleView for changing font: titleView.setTypeface(Typeface);
        }
    }
    

提交回复
热议问题