Android toolbar center title and custom font

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

    To use a custom title in your Toolbar you can add a custom title like :

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:elevation="5dp"
        app:contentInsetLeft="0dp"
        app:contentInsetStart="0dp"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
        app:theme="@style/ThemeOverlay.AppCompat.Dark">
    
    
            <LinearLayout
                android:id="@+id/lnrTitle"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center_horizontal"
                android:orientation="vertical">
    
                <TextView
                    android:id="@+id/txvHeader"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal|center"
                    android:gravity="center"
                    android:ellipsize="end"
                    android:maxLines="1"
                    android:text="Header"
                    android:textColor="@color/white"
                    android:textSize="18sp" />
    
    
            </LinearLayout>
    
    
    </android.support.v7.widget.Toolbar>
    

    Java Code:

    Toolbar toolbar = findViewById(R.id.toolbar);
    
    setSupportActionBar(toolbar);
    
    if (getSupportActionBar() == null)
        return;
    
    getSupportActionBar().setTitle("Title");
    
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    
    
    0 讨论(0)
  • 2020-11-22 05:02

    I spent several days searching for a universal solution. My toolbar working with android menu and nav icon.

    At first, you need create custom toolbar class. This class must have calculate title centered positions (paddings):

        class CenteredToolbar @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0)
        : Toolbar(context, attrs, defStyleAttr) {
    
        init {
            addOnLayoutChangeListener(object : View.OnLayoutChangeListener {
                override fun onLayoutChange(v: View?, left: Int, top: Int, right: Int, bottom: Int, oldLeft: Int, oldTop: Int, oldRight: Int, oldBottom: Int) {
                    val titleTextView = findViewById<TextView>(R.id.centerTitle)
    
                    val x = titleTextView.x.toInt()
                    val x2 = x + titleTextView.width
    
                    val fullWidth = width
                    val fullCenter = fullWidth / 2
    
                    val offsetLeft = Math.abs(fullCenter - x)
                    val offsetRight = Math.abs(x2 - fullCenter)
                    val differOffset = Math.abs(offsetLeft - offsetRight)
    
                    if (offsetLeft > offsetRight) {
                        titleTextView.setPadding(differOffset, 0, 0, 0)
                    } else if (offsetRight > offsetLeft) {
                        titleTextView.setPadding(0, 0, differOffset, 0)
                    }
    
                    removeOnLayoutChangeListener(this)
                }
            })
        }
    
        override fun setTitle(resId: Int) = getTitleView().setText(resId)
    
        override fun setTitle(title: CharSequence?) = getTitleView().setText(title)
    
        fun getTitleView(): TextView = findViewById(R.id.centerTitle)
    
    }
    

    Secondly, you need create layout toolbar:

    <CenteredToolbar xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/toolbar">
    
        <TextView
            android:id="@+id/centerTitle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    
    </CenteredToolbar>
    

    That's all

    0 讨论(0)
  • 2020-11-22 05:04

    This's just to help to join all pieces using @MrEngineer13 answer with @Jonik and @Rick Sanchez comments with the right order to help to achieve title centered easly!!

    The layout with TextAppearance.AppCompat.Widget.ActionBar.Title :

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay">
    
            <TextView
                android:id="@+id/toolbar_title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"                      
                style="@style/TextAppearance.AppCompat.Widget.ActionBar.Title"
                android:layout_gravity="center" />
    
        </android.support.v7.widget.Toolbar>
    

    The way to achieve with the right order:

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        TextView mTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);
    
        setSupportActionBar(toolbar);
        mTitle.setText(toolbar.getTitle());
    
        getSupportActionBar().setDisplayShowTitleEnabled(false);
    

    Please don't forget to upvote @MrEngineer13 answer !!!

    Here is a sample project ToolbarCenterTitleSample

    Hope to help somebody else ;)

    0 讨论(0)
  • 2020-11-22 05:04

    Here is title text dependant approach to find TextView instance from Toolbar.

      public static TextView getToolbarTitleView(ActionBarActivity activity, Toolbar toolbar){
        ActionBar actionBar = activity.getSupportActionBar();
        CharSequence actionbarTitle = null;
        if(actionBar != null)
            actionbarTitle = actionBar.getTitle();
        actionbarTitle = TextUtils.isEmpty(actionbarTitle) ? toolbar.getTitle() : actionbarTitle;
        if(TextUtils.isEmpty(actionbarTitle)) return null;
        // can't find if title not set
        for(int i= 0; i < toolbar.getChildCount(); i++){
            View v = toolbar.getChildAt(i);
            if(v != null && v instanceof TextView){
                TextView t = (TextView) v;
                CharSequence title = t.getText();
                if(!TextUtils.isEmpty(title) && actionbarTitle.equals(title) && t.getId() == View.NO_ID){
                    //Toolbar does not assign id to views with layout params SYSTEM, hence getId() == View.NO_ID
                    //in same manner subtitle TextView can be obtained.
                    return t;
                }
            }
        }
        return null;
    }
    
    0 讨论(0)
  • 2020-11-22 05:04

    Layout:

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar_top"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:minHeight="?attr/actionBarSize"
        android:background="@color/action_bar_bkgnd"
        app:theme="@style/ToolBarTheme" >
    
         <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Toolbar Title"
            android:layout_gravity="center"
            android:gravity="center"
            android:id="@+id/toolbar_title" />
    </android.support.v7.widget.Toolbar>
    

    Code:

        Toolbar mToolbar = parent.findViewById(R.id.toolbar_top);
        TextView mToolbarCustomTitle = parent.findViewById(R.id.toolbar_title);
    
        //setup width of custom title to match in parent toolbar
        mToolbar.postDelayed(new Runnable()
        {
            @Override
            public void run ()
            {
                int maxWidth = mToolbar.getWidth();
                int titleWidth = mToolbarCustomTitle.getWidth();
                int iconWidth = maxWidth - titleWidth;
    
                if (iconWidth > 0)
                {
                    //icons (drawer, menu) are on left and right side
                    int width = maxWidth - iconWidth * 2;
                    mToolbarCustomTitle.setMinimumWidth(width);
                    mToolbarCustomTitle.getLayoutParams().width = width;
                }
            }
        }, 0);
    
    0 讨论(0)
  • 2020-11-22 05:05

    Without toolbar TextView we can customize font by using below code

    getSupportActionBar().setDisplayShowTitleEnabled(false);
    or
    getActionBar().setDisplayShowTitleEnabled(false);
    
    public void updateActionbar(String title){
        SpannableString spannableString = new SpannableString(title);
        spannableString.setSpan(new TypefaceSpanString(this,  "futurastdmedium.ttf"),
                0, spannableString.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        mToolbar.setTitle(spannableString);
    }
    
    0 讨论(0)
提交回复
热议问题