Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
354 views
in Technique[技术] by (71.8m points)

java - How to set the ActionBar title in middle instead of the default left aligned position?

Trying to set the ActionBar title in middle instead of the default left aligned position. To do so, based on other answers this is what I've done:

    Toolbar myToolbar = (Toolbar) findViewById(R.id.toolbarDownloads);
    setSupportActionBar(myToolbar);
    if(getSupportActionBar()!=null)
    {
        getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        getSupportActionBar().setCustomView(R.layout.actionbar_layout);
    }

actionbar_layout.xml

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Downloads"
        android:layout_centerInParent="true"
        android:textColor="#000000"
        android:id="@+id/mytext"
        android:textSize="18sp" />

</RelativeLayout>

However, this does not produce the intended result (ie this renders the text however still is left aligned), what's wrong with this approach and how to fix this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

try this use custom Toolbar

<android.support.v7.widget.Toolbar
    android:id="@+id/ar_toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    app:layout_scrollFlags="exitUntilCollapsed"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Center"
        android:orientation="vertical">

        <TextView
             android:id="@+id/toolbar_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center" />
    </LinearLayout>

</android.support.v7.widget.Toolbar>

now in java file

private Toolbar toolbar;
toolbar = (Toolbar) findViewById(R.id.ar_toolbar);
TextView mTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);
 mTitle.setText("Nilesh Rathod");
setSupportActionBar(toolbar);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...