How to center the string of the bar action title and how to change its size?

Asked

Viewed 990 times

1

JAVA

package togglebutton.cursoandroid.com.togglebutton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

XML

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    tools:context="togglebutton.cursoandroid.com.togglebutton.MainActivity">

</android.support.constraint.ConstraintLayout>

1 answer

1

I believe this is a very pertinent doubt in the development for Android, because it is not enough to just try to apply a Gravity in it, because the Toolbar, being a ViewGroup, is occupied by other elements (actions Buttons, for example) that end robbing the title space of it. If you apply a Gravity directly to center the title of Toolbar, she came to get a little crooked, because of other views who are also in the Toolbar.

I use a very interesting method that works in all cases. First, I create a component to serve as a title for my Toolbar.

res/layout/toolbar_custom_content.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toolbarTitle"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:text="@string/app_name"
    android:textColor="#212121"
    android:textSize="16sp" 
    />

You can modify this component however you want. Color, text... is all on your own.

Now, normally add your Toolbar in its layout, without having to make any modifications. Just add the View.

res/layout/activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    tools:context="togglebutton.cursoandroid.com.togglebutton.MainActivity"
    >

    <android.support.v7.widget.Toolbar 
        android:id="@+id/toolbar"
        android:layout_width="0dp"
        android:layout_height="?android:actionBarSize"
        android:title="@string/app_name"
        app:elevation="1dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent
        app:layout_constraintTop_toTopOf="parent"
    />


 </android.support.constraint.ConstraintLayout>

Ready. Now you’ve got your main layout built, let’s go to code.

Mainactivity class

public class MainActivity extends AppCompatActivity {

    Toolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setupToolbar();
    }

    private void setupToolbar() {
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false); // remove o título original da Toolbar
        getSupportActionBar().setDisplayShowCustomEnabled(true); // permite que possamos adicionar custom layouts na toolbar

        View viewTitle = getLayoutInflater().inflate(R.layout.toolbar_custom_view, null); 
        // Lembra da TextView que criamos anteriormente para ser usado como título? 
        // Então, iremos carregar ela, configurar algumas coisas e depois mandar para a Toolbar.

        ActionBar.LayoutParams viewParams = new ActionBar.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT);
        // Nesta parte estamos carregando alguns parâmetro de configuração
        // Eles serão aplicados em nossa TextView, para que ela possa estar corretamente centralizada.

        viewParams.gravity = viewParams.gravity & ~Gravity.HORIZONTAL_GRAVITY_MASK or Gravity.CENTER_HORIZONTAL
        // Pegamos a 'gravity' atual da view e aplicamos o operador bitwise AND com o inverso dos bits de Gravity.HORIZONTAL_GRAVITY_MASK
       // Isto resolve o problema do título estar com um espaço para a direita quando há um botão de voltar na Toolbar, por exemplo

       getSupportActionBar().setCustomView(viewTitle, viewParams);
       getSupportActionBar().setDisplayOptions(
               getSupportActionBar().getDisplayOptions(),
               ActionBar.DISPLAY_SHOW_CUSTOM
       );
    }
}

That’s it. Your Toolbar has a properly centralized title and you will no longer have problems with an incorrect centralization. You can test the common way, for example try adding a back button on Toolbar and then centralize a TextView. You will notice that this is more aligned to the right, rather than being in the center. This is because of the space occupied by some views.

I understand that the answer has gotten a little big and that the approach too. But know that this method is efficient and you can modify it to avoid both Boilerplate. You don’t have to do this in all your activities, just make an abstract class that does what we did here in this answer. The rest is history.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.