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:
- Eliminación de un tono de llamada mediante programación en android
- Barra de título de Android dejando espacio cuando se reanuda la aplicación
- Android: ¿Cómo establecer un contexto generadoMenú título?
- ¿Cómo puedo detectar un clic en el título de ActionBar?
- Altura establecida para Android de la barra de título personalizada
ClassCastException : com.android.internal.widget.ActionBarView can not be cast to android.widget.TextView.
Cualquier otra solución .. Cualquier ayuda será apreciada.
- Título de la acción: Mostrar Título AND Icon
- Cómo crear un ActionBar personalizado con el cajón de navegación
- Título de la actividad de Android vs Título de ActionBar
- Centro Alinee el título en la barra de acción utilizando estilos en android.
- Cómo deshabilitar la barra de estado o barra de notificación, pero no deshabilitar la barra de título en android?
- La barra de título sigue apareciendo, incluso con requestWindowFeature o android: theme
- Calcule el rumbo de la brújula / rumbo a la ubicación en Android
- Añadir leyenda a la imagen en el nuevo whatsapp ver 2.11.399 (android)
Puede crear un diseño personalizado y aplicarlo a la barra de acción.
Para ello, siga estos 2 sencillos pasos:
-
Código Java
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); getSupportActionBar().setCustomView(R.layout.actionbar);
Donde R.layout.actionbar
es la siguiente distribución.
-
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>