nlmm01
nlmm01

Reputation: 891

Center layouts in Toolbar Android

Please look at attached image. I am using support toolbar and setting it to support actionbar. But the Textview inside Toolbar is not taking full width(as seen in layout bounds). Hence I am unable to center it horizontally. Please help.

Requirement

app_bar XML:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:id="@+id/app_bar"
    android:layout_height="wrap_content"
    android:minHeight = "?attr/actionBarSize">

    <TextView
        android:layout_marginTop="100dp"
        android:id="@+id/list_title"
        android:layout_width="match_parent"
        android:text="PERFECT SPRING"
        android:textStyle="bold"
        android:gravity="center"
        android:textColor="#FFF"
        android:layout_height="wrap_content" />


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

fragment:

View rootView = inflater.inflate(R.layout.fragment_main, container, false);
toolbar = (Toolbar) rootView.findViewById(R.id.app_bar);
ActionBarActivity activity = (ActionBarActivity) getActivity();
activity.setSupportActionBar(toolbar);
activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
activity.getSupportActionBar().setTitle("");
toolbar.setBackgroundResource(R.drawable.city);
return rootView;

In play store, I see the views centered:

centered play button

Upvotes: 1

Views: 725

Answers (3)

RenatoIvancic
RenatoIvancic

Reputation: 2092

This is positioning problem, nothing to do specifically with the Android Toolbar itself.

You are setting android:layout_width="match_parent" which takes whole space that is left between back arrow and options icon. Then with the android:gravity="center" you center the text inside the TextView which itself is not centered.

The correct way is to set the TextView width to android:layout_width="wrap_content" and set the android:layout_gravity="center_horizontal" so the whole view is then centered in horizontal direction.

This should work:

<TextView
    android:layout_marginTop="100dp"
    android:id="@+id/list_title"
    android:layout_width="wrap_content"
    android:text="PERFECT SPRING"
    android:textStyle="bold"
    android:layout_gravity="center_horizontal"
    android:textColor="#FFF"
    android:layout_height="wrap_content" />

Upvotes: 3

Kirankumar Zinzuvadia
Kirankumar Zinzuvadia

Reputation: 1249

You have to set image with same size on right or create own custom FrameLayout/Relative Layout to show like that.

I think custom View would be better for your app.

Upvotes: 0

Navdroid
Navdroid

Reputation: 1549

Try and use getSupportActionBar().setTitle("My title");

Upvotes: 0

Related Questions