Android: How to Center title in ToolBar

后端 未结 19 1917
执念已碎
执念已碎 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:44

    I slightly modified the Toolbar source to make the title centre aligned.

    public class CenterTitleToolbar extends Toolbar {
        private AppCompatTextView titleTextView;
    
    
        public CenterTitleToolbar(Context context) {
            super(context);
        }
    
        public CenterTitleToolbar(Context context, @Nullable AttributeSet attrs) {
            super(context, attrs);
        }
    
        public CenterTitleToolbar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
        }
    
        @Override
        public void setTitle(CharSequence title) {
            if (!TextUtils.isEmpty(title)) {
                if (titleTextView == null) {
                    final Context context = getContext();
                    titleTextView = new AppCompatTextView(context);
                    titleTextView.setSingleLine();
                    titleTextView.setEllipsize(TextUtils.TruncateAt.END);
                    titleTextView.setTextAppearance(context, R.style.TextAppearance_MaterialComponents_Headline6);
                    final LayoutParams lp = generateDefaultLayoutParams();
                    lp.gravity = Gravity.CENTER;
                    titleTextView.setLayoutParams(lp);
                }
                if (titleTextView.getParent() != this) {
                    addSystemView(titleTextView);
                }
            } else if (titleTextView != null && titleTextView.getParent() == this) {
                removeView(titleTextView);
            }
            if (titleTextView != null) {
                titleTextView.setText(title);
            }
        }
    
        private void addSystemView(View v) {
            final ViewGroup.LayoutParams vlp = v.getLayoutParams();
            final LayoutParams lp;
            if (vlp == null) {
                lp = generateDefaultLayoutParams();
            } else if (!checkLayoutParams(vlp)) {
                lp = generateLayoutParams(vlp);
            } else {
                lp = (LayoutParams) vlp;
            }
            addView(v, lp);
        }
    
    }
    

    Text Style TextAppearance_MaterialComponents_Headline6 is included in the new Android Material library.

    0 讨论(0)
  • 2020-11-27 19:45

    I didn't understand you Question Completely .. but i found Solution Like this

    To use a custom title in your Toolbar all you need to do is remember is that Toolbar is just a fancy ViewGroup so you can add a custom title like so:

    <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="wrap_content"
            android:layout_height="wrap_content"
            android:text="Toolbar Title"
            android:layout_gravity="center"
            android:id="@+id/toolbar_title" />
    </android.support.v7.widget.Toolbar>
    

    This means that you can style the TextView however you would like because it's just a regular TextView. So in your activity you can access the title like so:

    Toolbar toolbarTop = (Toolbar) findViewById(R.id.toolbar_top);
    TextView mTitle = (TextView) toolbarTop.findViewById(R.id.toolbar_title);
    
    0 讨论(0)
  • 2020-11-27 19:47

    ToolBar is a View Group. so To Center Align The text Use

    app_bar.xml

    <?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/in.chabu"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        app:theme="@style/ToolBarTheme" 
        android:minHeight="?attr/actionBarSize">
    
         <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/title_activity_sign_up"
            android:layout_gravity="center"
            android:id="@+id/toolbar_title" 
            android:textStyle="bold"
            android:textColor="@android:color/white"/>
    
    </android.support.v7.widget.Toolbar>
    

    activity_sign_up

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="in.chabu.activities.SignUpActivity" >
    
        <include 
            android:id="@+id/tool_bar"
            layout="@layout/app_bar"/>
    
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/tool_bar"
            android:text="@string/hello_world" />
    
    </RelativeLayout>
    

    Avtivity

    public class SignUpActivity extends ActionBarActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_sign_up);
    
            Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar);
    
            setSupportActionBar(toolbar);
    
            getSupportActionBar().setDisplayShowTitleEnabled(false);
        }
    
    
    }
    
    0 讨论(0)
  • 2020-11-27 19:53

    for kotlin users from @user2137020 answer:

    package com.example.safetyofficer.view
    
    import android.content.Context
    import android.util.AttributeSet
    import android.widget.TextView
    import androidx.appcompat.widget.Toolbar
    import com.example.safetyofficer.R
    
    
    class CustomToolbar @JvmOverloads constructor(
        context: Context,
        attrs: AttributeSet? = null,
        defStyleAttr: Int = R.attr.toolbarStyle
    ) :
        Toolbar(context, attrs, defStyleAttr) {
        private val titleView: TextView = TextView(getContext())
    
        override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
            super.onLayout(changed, l, t, r, b)
            titleView.x = (width - titleView.width) / 2.toFloat()
        }
    
        override fun setTitle(title: CharSequence) {
            titleView.text = title
        }
    
        init {
            val textAppearanceStyleResId: Int
            val a = context.theme.obtainStyledAttributes(
                attrs,
                intArrayOf(R.attr.titleTextAppearance),
                defStyleAttr,
                0
            )
            textAppearanceStyleResId = try {
                a.getResourceId(0, 0)
            } finally {
                a.recycle()
            }
            if (textAppearanceStyleResId > 0) {
                titleView.setTextAppearance(textAppearanceStyleResId)
            }
            addView(titleView, LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT))
        }
    }
    
    0 讨论(0)
  • 2020-11-27 19:53

    I think this will work.

    name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"
    

    change your base theme in values/styles.xml

    Than add your Toolbar manually like this

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        android:theme="?attr/actionBarTheme"
        app:title="Title"
        app:titleMarginStart="155dp"
        app:titleTextColor="@android:color/white" />
    

    But this is not good idea this not works well.

    0 讨论(0)
  • 2020-11-27 19:55

    You can force the toolbar to the center by wrapping title and level right padding which has default left padding for title. Then put background color to the parent of toolbar and that way part which is cut out by wrapping title is in the same color(white in my example):

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/white">
    
                <android.support.v7.widget.Toolbar
                   android:id="@+id/toolbar"
                   android:layout_width="wrap_content"
                   android:layout_height="56dp"
                   android:layout_gravity="center_horizontal"
                   android:paddingEnd="15dp"
                   android:paddingRight="15dp"
                   android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
                   app:titleTextColor="@color/black"/>
    
    </android.support.design.widget.AppBarLayout>
    
    0 讨论(0)
提交回复
热议问题