web-dev-qa-db-fra.com

Comment aligner le titre au centre d'ActionBar dans le thème par défaut (Theme.Holo.Light)

J'ai beaucoup cherché mais je ne trouve pas de solution. Comment puis-je définir le titre au centre de ActionBar au lieu d'être aligné à gauche J'ai utilisé le code ci-dessous pour définir le titre au centre:

ViewGroup decorView= (ViewGroup) this.getWindow().getDecorView();
LinearLayout root= (LinearLayout) decorView.getChildAt(0);
FrameLayout titleContainer= (FrameLayout) root.getChildAt(0);
TextView title= (TextView) titleContainer.getChildAt(0);
title.setGravity(Gravity.CENTER);

Mais cela donne une erreur comme ci-dessous:

ClassCastException : com.Android.internal.widget.ActionBarView can not 
be cast to Android.widget.TextView.

Toute autre solution ..Toute aide sera appréciée.

41
Ponting

Vous pouvez créer une présentation personnalisée et l'appliquer à la barre d'actions.

Pour ce faire, suivez ces 2 étapes simples:

  1. Code Java

    getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
    getSupportActionBar().setCustomView(R.layout.actionbar);
    

R.layout.actionbar est la disposition suivante.

  1. XML

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
        Android:layout_width="match_parent"
        Android:layout_height="wrap_content"
        Android:layout_gravity="center"
        Android:orientation="vertical">
    
    <TextView
        Android:layout_width="wrap_content"
        Android:layout_height="wrap_content"
        Android:layout_gravity="center"
        Android:id="@+id/action_bar_title"
        Android:text="YOUR ACTIVITY TITLE"
        Android:textColor="#ffffff"
        Android:textSize="24sp" />
    </LinearLayout>
    

Cela peut être aussi complexe que vous le souhaitez. Essaye le!

MODIFIER:

Pour définir background, vous pouvez utiliser la propriété Android:background dans la présentation du conteneur (LinearLayout dans ce cas). Vous devrez peut-être définir la hauteur de la structure Android:layout_height sur match_parent au lieu de wrap_content

De plus, vous pouvez également y ajouter un LOGO/IC&OCIRC;NE. Pour ce faire, ajoutez simplement ImageView dans votre présentation et définissez la propriété Android:orientation sur l'orientation de la présentation sur horizontal (ou utilisez simplement un RelativeLayout et gérez-le vous-même).

Pour modifier le titre de la barre d'action personnalisée ci-dessus de manière dynamique, procédez comme suit: 

TextView title=(TextView)findViewById(getResources().getIdentifier("action_bar_title", "id", getPackageName()));
title.setText("Your Text Here");
119
Stefano Munarini

Découvrez la nouvelle barre d'outils sur la classe de bibliothèque de support dans la mise à jour Lollipop, vous pouvez concevoir une barre d'action en ajoutant une barre d'outils à votre présentation.

ajouter ces éléments dans le thème de votre application

 <item name="Android:windowNoTitle">true</item>
    <item name="windowActionBar">false</item>

Créez votre barre d'outils dans une mise en page et incluez votre texte au centre de la conception de votre barre d'outils 

<Android.support.v7.widget.Toolbar
    xmlns:Android="http://schemas.Android.com/apk/res/Android"
    Android:id="@+id/toolbar"
    Android:layout_width="match_parent"
    Android:layout_height="wrap_content"
    Android:background="@color/acbarcolor">
      <RelativeLayout
         Android:layout_width="match_parent"
         Android:layout_height="wrap_content" >

     <TextView
         Android:id="@+id/toolbar_title"
         Android:layout_width="wrap_content"
         Android:layout_height="wrap_content"
         Android:layout_centerHorizontal="true"
         Android:layout_centerVertical="true"
         Android:text="@string/app_name"
         Android:textColor="#ffffff"
         Android:textStyle="bold" />



     </RelativeLayout>

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

ajoutez votre barre d'action en tant que barre d'outils

 toolbar = (Toolbar) findViewById(R.id.toolbar);
        if (toolbar != null) {
            setSupportActionBar(toolbar);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }

assurez-vous que vous avez besoin d'inclure la barre d'outils sur votre fichier de ressources comme ceci

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

       <include
           Android:layout_width="match_parent"
           Android:layout_height="wrap_content"
           layout="@layout/toolbar" />

    <Android.support.v4.widget.DrawerLayout

    xmlns:Android="http://schemas.Android.com/apk/res/Android"
     xmlns:tools="http://schemas.Android.com/tools"
    Android:id="@+id/drawer_layout"
    Android:layout_width="match_parent"
    Android:layout_height="match_parent">

    <!-- Framelayout to display Fragments -->



    <FrameLayout
        Android:id="@+id/frame_container"
        Android:layout_width="match_parent"
        Android:layout_height="match_parent">
        <include

            Android:layout_width="match_parent"
            Android:layout_height="match_parent"
            layout="@layout/homepageinc" />



         </FrameLayout>
         <fragment
            Android:id="@+id/fragment1"
             Android:layout_gravity="start"
            Android:name="com.shouldeye.homepages.HomeFragment"
            Android:layout_width="250dp"
            Android:layout_height="match_parent" />
    </Android.support.v4.widget.DrawerLayout>

</LinearLayout>
7
Jinu

Il semble qu'il n'y ait aucun moyen de le faire sans une vue personnalisée. Vous pouvez obtenir la vue du titre:

View decor = getWindow().getDecorView();
TextView title = (TextView) decor.findViewById(getResources().getIdentifier("action_bar_title", "id", "Android"));

Mais changer de gravity ou layout_gravity n'a pas d'effet. Le problème dans la ActionBarView, qui utilise ses propres enfants alors le changement des paramètres de disposition de ses enfants n'a pas non plus d'effet ...

ViewGroup actionBar = (ViewGroup) decor.findViewById(getResources().getIdentifier("action_bar", "id", "Android"));
View v = actionBar.getChildAt(0);
ActionBar.LayoutParams p = new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
p.gravity= Gravity.CENTER;
v.setLayoutParams(p);
v.setBackgroundColor(Color.BLACK);
7
esentsov

Je sais que ma réponse n’est pas à l’heure, mais c’est purement le code xml requis…
Ceci est pour une utilisation dans Activity

public void setTitle(String title){
    getSupportActionBar().setHomeButtonEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    TextView textView = new TextView(this);
    textView.setText(title);
    textView.setTextSize(20);
    textView.setTypeface(null, Typeface.BOLD);
    textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
    textView.setGravity(Gravity.CENTER);
    textView.setTextColor(getResources().getColor(R.color.white));
    getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
    getSupportActionBar().setCustomView(textView);
}


Ceci est pour une utilisation dans Fragment

public void setTitle(String title){
    ((AppCompatActivity)getActivity()).getSupportActionBar().setHomeButtonEnabled(true);
    ((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    TextView textView = new TextView(getActivity());
    textView.setText(title);
    textView.setTextSize(20);
    textView.setTypeface(null, Typeface.BOLD);
    textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
    textView.setGravity(Gravity.CENTER);
    textView.setTextColor(getResources().getColor(R.color.white));
    ((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
    ((AppCompatActivity)getActivity()).getSupportActionBar().setCustomView(textView);
}
4
Umar Ata

si vous utilisez la barre d'outils le juste ajouter

Android:layout_gravity="center_horizontal"

Sous la barre d'outils Juste comme cet extrait

 <Android.support.design.widget.AppBarLayout
    Android:layout_width="match_parent"
    Android:layout_height="wrap_content"
    Android:theme="@style/AppTheme.AppBarOverlay">

    <Android.support.v7.widget.Toolbar
        Android:id="@+id/toolbar"
        Android:layout_width="match_parent"
        Android:layout_height="?attr/actionBarSize"
        Android:background="@color/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay">

        <TextView
            Android:id="@+id/tvTitle"
            Android:layout_width="wrap_content"
            Android:layout_height="wrap_content"
            Android:layout_gravity="center_horizontal"    //Important 
            Android:textColor="@color/whitecolor"
            Android:textSize="20sp"
            Android:textStyle="bold" />
    </Android.support.v7.widget.Toolbar>

</Android.support.design.widget.AppBarLayout>
3
Darshan Khatri

Cela fonctionne réellement:

 getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
 getActionBar().setCustomView(R.layout.custom_actionbar);
  ActionBar.LayoutParams p = new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        p.gravity = Gravity.CENTER;

Vous devez définir la disposition custom_actionbar.xml qui correspond à vos besoins, par exemple. :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
    Android:layout_width="match_parent"
    Android:layout_height="50dp"
    Android:background="#2e2e2e"
    Android:orientation="vertical"
    Android:gravity="center"
    Android:layout_gravity="center">

    <ImageView
        Android:id="@+id/imageView1"
        Android:layout_width="wrap_content"
        Android:layout_height="wrap_content"
        Android:src="@drawable/top_banner"
        Android:layout_gravity="center"
        />
</LinearLayout>
2
Roshan Ramtel

Code Java: Écrit ceci dans onCreate ()
getSupportActionBar().setDisplayShowCustomEnabled(true);getSupportActionBar().setCustomView(R.layout.action_bar);

et pour votre vue personnalisée, utilisez simplement FrameLayout, East Peasy!
Android.support.v7.widget.Toolbar est une autre option

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
    Android:layout_width="match_parent"
    Android:layout_height="match_parent">

    <TextView
        Android:layout_width="wrap_content"
        Android:layout_height="wrap_content"
        Android:layout_gravity="left|center_vertical"
        Android:textAppearance="?android:attr/textAppearanceLarge"
        Android:text="@string/app_name"
        Android:textColor="@color/black"
        Android:id="@+id/textView" />
</FrameLayout>
1
Amir

Je pense qu'en plaçant les vues sur la barre d'action, vous obtiendrez ce que vous voulez. La disposition de la barre d'action lorsque les paramètres de disposition sont définis sur le parent fonctionne comme layout_weight = "value") nous pouvons définir notre vue où nous voulons:

    actionBar = getSupportActionBar(); 
    actionBar.setDisplayShowCustomEnabled(true); 

    LayoutInflater ll = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    LinearLayout linearLayout = (LinearLayout) ll.inflate(R.layout.custom_actionbar, null);
    //inner layout within above linear layout
    LinearLayout inner = (LinearLayout) linearLayout.findViewById(R.id.inner_linear_ractionbar);
    inner.setMinimumWidth(getWidth() * 2 / 10);
    // we will set our textview to center and display there some text
    TextView t = (TextView) linearLayout.findViewById(R.id.center_text);
    t.setWidth(getWidth() * 6 / 10);


    Button b = (Button) linearLayout.findViewById(R.id.edit_button);
    b.setWidth(getWidth() *3/ 20);

    ImageButton imageButton = (ImageButton) linearLayout.findViewById(R.id.action_bar_delete_item);
    imageButton.setMinimumWidth(deviceUtils.getWidth() / 20);

et voici la méthode getWidth ():

 public int getWidth() { 
    DisplayMetrics dm = new DisplayMetrics();
     mActivity.getWindowManager().getDefaultDisplay().getMetrics(dm);
    return dm.widthPixels; 
   }
1
support_ms

Vous pouvez forcer la barre d’outils en encapsulant le rembourrage droit et de niveau qui contient le remplissage gauche par défaut pour le titre. Ensuite, placez la couleur d’arrière-plan dans le parent de la barre d’outils. Ainsi, la partie découpée en enveloppant le titre est de la même couleur (blanc dans mon exemple):

<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
tompadre

la solution est basée sur ces choses:

  • vous devez utiliser votre propre classe qui étend la barre d'outils (support.v7.widget.toolbar) 
  • vous devez remplacer une méthode Toolbar # addView

qu'est ce que ça fait: 

lorsque la première barre d'outils exécute #setTitle, elle crée AppCompatTextView et l'utilise pour afficher le texte du titre.

lorsque la AppCompatTextView est créée, la barre d'outils (en tant que ViewGroup) l'ajoute à sa propre hiérarchie avec la méthode #addView.

aussi, tout en essayant de trouver une solution, j’ai remarqué que la largeur de mise en page de la fenêtre de visualisation textview était définie sur "wrap_content"; 

MyToolbar.kt, en sautant des choses sans rapport (constructeurs/importations):

class MyToolbar : Toolbar {

  override fun addView(child: View, params: ViewGroup.LayoutParams) {
    if (child is TextView) {
        params.width = ViewGroup.LayoutParams.MATCH_PARENT
        child.textAlignment= View.TEXT_ALIGNMENT_CENTER
    }
    super.addView(child, params)
  }
}

"effets secondaires" possibles - ceci s'appliquera aussi au "sous-titre"

0
dmz9

J'ai eu le même problème, et à cause du bouton "Accueil" ajouté automatiquement dans la barre d'outils, mon texte n'a pas été saisi exactement.

Je l'ai corrigé de manière sale mais cela fonctionne bien dans mon cas. J'ai simplement ajouté une marge à droite de mon TextView pour compenser le bouton d'accueil situé à gauche. Voici ma disposition de la barre d'outils:

<Android.support.v7.widget.Toolbar
    xmlns:Android="http://schemas.Android.com/apk/res/Android"
    xmlns:app="http://schemas.Android.com/apk/res-auto"
    Android:elevation="1dp"
    Android:id="@+id/toolbar"
    Android:layout_width="match_parent"
    Android:layout_height="?attr/actionBarSize"
    app:layout_collapseMode="pin"
    Android:gravity="center"
    Android:background="@color/mainBackgroundColor"
    Android:fitsSystemWindows="true" >

    <com.lunabee.common.utils.LunabeeShadowTextView
        Android:id="@+id/title"
        Android:layout_width="match_parent"
        Android:layout_height="wrap_content"
        Android:layout_marginRight="?attr/actionBarSize"
        Android:gravity="center"
        style="@style/navigation.toolbar.title" />

</Android.support.v7.widget.Toolbar>
0
Olivier Berni