Cómo alinear el título en el centro de ActionBar en el tema predeterminado (Theme.Holo.Light)

Busqué mucho, pero no puedo encontrar una manera, ¿Cómo puedo establecer después título en el centro de ActionBar en lugar de alineado a la izquierda. Utilicé debajo del código para fijar el título en el centro:

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); 

Pero da el error como abajo:

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

Cualquier otra solución .. Cualquier ayuda será apreciada.

Puede crear un diseño personalizado y aplicarlo a la barra de acción.

Para ello, siga estos 2 sencillos pasos:

  1. Código Java

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

Donde R.layout.actionbar es la siguiente distribución.

  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> 

Puede ser tan complejo como quieras. ¡Pruébalo!

EDITAR:

Para establecer el background puede utilizar la propiedad android:background en el diseño del contenedor (LinearLayout en ese caso). Puede que necesite establecer la altura del diseño android:layout_height para match_parent lugar de wrap_content .

Además, también puede agregar un LOGO / ICON a él. Para ello, simplemente agregue un ImageView dentro de su diseño, y defina la orientación de la propiedad android:orientation horizontal (o simplemente use RelativeLayout y administre usted mismo).

Para cambiar dinámicamente el título de la barra de acción personalizada anterior, haga lo siguiente:

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

Parece que no hay manera de hacer esto sin vista personalizada. Puede obtener la vista de título:

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

Pero el cambio de gravity o gravity layout_gravity no tiene efecto. El problema en el ActionBarView , que el diseño de sus hijos por sí mismo tan cambiante de los params de diseño de sus hijos también no tiene un efecto. Para ver esto escriba el siguiente código:

 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); 

Echa un vistazo a la nueva barra de herramientas en la clase de biblioteca de soporte en la actualización de Lollipop puede diseñar la barra de acción mediante la adición de barra de herramientas en su diseño

Agregue estos elementos al tema de su aplicación

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

Crea tu barra de herramientas en un diseño e incluye tu texto en el centro de tu barra de herramientas

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

Agrega tu barra de acción como barra de herramientas

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

Asegúrese de que debe incluir la barra de herramientas en su archivo de recursos como este

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

Esto realmente funciona:

  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; 

Usted tiene que definir la disposición del custom_actionbar.xml que es según su requisito eg:

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

Creo que al posicionar las vistas en la barra de acción llegarás a lo que quieres. En el diseño de la barra de acción cuando los parámetros de diseño se ajustan a coincidir con el padre, no coincide con el ancho total, es por eso que lo hice programáticamente donde tengo éxito. = "Value") podemos establecer nuestra vista donde queramos:

  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); 

Y aquí está el método getWidth ():

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

Código Java: escriba esto en onCreate ()
getSupportActionBar().setDisplayShowCustomEnabled(true); getSupportActionBar().setCustomView(R.layout.action_bar);

Y para usted vista de encargo, utilice simplemente FrameLayout, este peasy!
Android.support.v7.widget.Toolbar es otra opción

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

Sé que mi respuesta no es a tiempo, pero esto es puramente código no xml requerido.
Esto es para su uso en la 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); } 

Esto es para uso en 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); } 

Tuve el mismo problema, y ​​debido a que el botón "Inicio" se agregó automáticamente en la barra de herramientas, mi texto no se escribió exactamente.

Lo arreglé el camino sucio pero funciona bien en mi caso. Simplemente agregé un margen a la derecha de mi TextView para compensar el botón de inicio de la izquierda. Aquí está mi diseño de barra de herramientas:

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

Puede forzar la barra de herramientas mediante el envolvente del título y el nivel de relleno derecho que tiene el relleno izquierdo por defecto para el título. Que poner el color de fondo a los padres de la barra de herramientas y esa parte de la manera que se corta por el título de envoltura está en el mismo color (blanco en mi ejemplo):

 <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> 
  • Cambiar el texto y el color de fondo en la barra de título (Android)?
  • Android: la barra de progreso en el título de la ventana no se muestra
  • ¿Cómo puedo añadir un spinner a la barra de título de una actividad?
  • Cómo cambiar el color de la barra de título sin tema
  • Cómo ocultar la barra de título desde el principio
  • Cómo mostrar el título de la barra de acciones de Android sin que se produzca el truncamiento
  • Android: centra el título de la barra de herramientas
  • Cómo quitar la barra de título de Actividad que extiende ActionBarActivity o AppcompatActivity con tema de diálogo
  • Cambio de la barra de título de Android de fondo
  • Android: cambia el título en ActionBar desde el Gaveta de navegación
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.