Establecer el color de fondo del título


En mi aplicación Android quiero que la barra de título estándar/básico cambie de color.

Para cambiar el color del texto que tiene setTitleColor(int color), ¿hay alguna manera de cambiar el color de fondo de la barra?

Author: brc, 2010-02-12

10 answers

Este hilo te ayudará a empezar a construir tu propia barra de título en un archivo xml y a usarla en tus actividades

Editar

Aquí hay un breve resumen del contenido del enlace anterior-Esto es solo para establecer el color del texto y el fondo de la barra de título - sin redimensionar, sin botones, solo la muestra más simple

res / layout / mytitle.xml - Esta es la vista que representará el título bar

<?xml version="1.0" encoding="utf-8"?>
<TextView
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/myTitle"
  android:text="This is my new title"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:textColor="@color/titletextcolor"
   />

res / valores / temas.xml - Queremos mantener el tema predeterminado de Android y solo tenemos que cambiar el color de fondo del fondo del título. Así que creamos un tema que hereda el tema predeterminado y establecemos el estilo de fondo a nuestro propio estilo.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="customTheme" parent="android:Theme"> 
        <item name="android:windowTitleBackgroundStyle">@style/WindowTitleBackground</item>   
    </style> 
</resources>

res / valores / estilos.xml - Aquí es donde configuramos el tema para usar el color que queremos para el fondo del título

<?xml version="1.0" encoding="utf-8"?>
<resources> 
   <style name="WindowTitleBackground">     
        <item name="android:background">@color/titlebackgroundcolor</item>                   
    </style>
</resources>

res / valores / colores.xml - Establezca aquí el color que want

<?xml version="1.0" encoding="utf-8"?>
<resources>   
    <color name="titlebackgroundcolor">#3232CD</color>
    <color name="titletextcolor">#FFFF00</color>
</resources>

En el AndroidManifest.xml , establece el atributo theme en la aplicación (para toda la aplicación) o en la actividad (solo esta actividad) tags

<activity android:name=".CustomTitleBar" android:theme="@style/customTheme" ...

Desde la Actividad (llamada CustomTitleBar) :

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.main);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.mytitle);

}
 182
Author: ccheneson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-03-05 22:34:10

Gracias por esta explicación clara, sin embargo, me gustaría añadir un poco más a su respuesta haciendo una pregunta vinculada (realmente no quiero hacer un nuevo post ya que este es el sótano de mi pregunta).

Estoy declarando mi barra de título en una Superclase de la que, todas mis otras actividades son niños, tener que cambiar el color de la barra solo una vez. También me gustaría añadir un icono y cambiar el texto en la barra. He hecho algunas pruebas, y se las arregló para cambiar uno o el otro, pero no ambos al mismo tiempo (usando setFeatureDrawable y setTitle). La solución ideal sería, por supuesto, seguir la explicación en el hilo dado en el enlace, pero como estoy declarando en una superclase, tengo un problema debido al diseño en setContentView y el R. id.myCustomBar, porque si recuerdo bien puedo llamar a setContentView solo una vez...

EDITAR Encontré mi respuesta:

Para aquellos que, como yo, les gusta trabajar con superclases porque es genial para obtener un menú disponible en todas partes en una aplicación, funciona igual aquí.

Simplemente agrega esto a tu superclase:

requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
    setContentView(R.layout.customtitlebar);
    getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.customtitlebar);
    customTitleText = (TextView) findViewById(R.id.customtitlebar);

(debe declarar textview como variable de clase protegida)

Y entonces el poder de esto es que, en todas partes en su aplicación (si por ejemplo todas sus actividades son niños de esta clase), solo tiene que llamar

customTitleText.setText("Whatever you want in title");

Y tu barra de título será editada.

El XML asociado en mi caso es (R. layout.barra personalizada):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:background="@color/background">
<ImageView android:layout_width="25px" android:layout_height="25px"
    android:src="@drawable/icontitlebar"></ImageView>
<TextView android:id="@+id/customtitlebar"
    android:layout_width="wrap_content" android:layout_height="fill_parent"
    android:text="" android:textColor="@color/textcolor" android:textStyle="bold"
    android:background="@color/background" android:padding="3px" />
</LinearLayout>
 18
Author: Sephy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-04-27 14:37:09

Hay otra forma de cambiar el color de fondo, sin embargo, es un truco y podría fallar en futuras versiones de Android si se cambia la jerarquía de vistas de la ventana y su título. Sin embargo, el código no se bloqueará, solo se perderá la configuración del color deseado, en tal caso.

En tu Actividad, como onCreate, haz:

View titleView = getWindow().findViewById(android.R.id.title);
if (titleView != null) {
  ViewParent parent = titleView.getParent();
  if (parent != null && (parent instanceof View)) {
    View parentView = (View)parent;
    parentView.setBackgroundColor(Color.rgb(0x88, 0x33, 0x33));
  }
}
 11
Author: mikeplate,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-12-02 19:26:41
protected void onCreate(Bundle savedInstanceState) {        
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    View titleView = getWindow().findViewById(android.R.id.title);
    if (titleView != null) {
      ViewParent parent = titleView.getParent();
      if (parent != null && (parent instanceof View)) {
        View parentView = (View)parent;
        parentView.setBackgroundColor(Color.RED);
      }
    }

En el código anterior puedes probar puedes usar title en lugar de titlebar esto afectará a toda la actividad en su aplicación

 6
Author: Pratishtha Goriya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-04-05 11:49:03

Este código ayuda a cambiar el fondo de la barra de título mediante programación en Android. Cambie el color a cualquier color que desee.

public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_layout);
    getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#1c2833")));

}
 5
Author: Edwinfad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-21 20:10:26

Supongo que no. Puede crear actividad sin título y crear su propia barra de título en diseño de actividad.

Marque este , Línea 63 y abajo:

getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title_1)

Establece customview en lugar de la vista de título predeterminada.

 2
Author: skyman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-15 13:41:44

Echa un vistazo a platforms/android-2.1/data/res/layout/screen.xml del SDK. Parece definir un título. Con frecuencia puede examinar diseños como este y pedir prestado el style="?android:attr/windowTitleStyle" estilos que luego puede usar y anular en sus propias vistas de texto.

Es posible que incluso pueda seleccionar el título para el ajuste directo haciendo:

TextView title = (TextView)findViewById(android.R.id.title);
 2
Author: Steve Pomeroy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-17 19:43:56

Intente con el siguiente código

View titleView = getWindow().findViewById(android.R.id.title);
    if (titleView != null) {
      ViewParent parent = titleView.getParent();
      if (parent != null && (parent instanceof View)) {
        View parentView = (View)parent;
        parentView.setBackgroundColor(Color.RED);
      }
    }

También use este enlace es muy útil: http://nathanael.hevenet.com/android-dev-changing-the-title-bar-background /

 2
Author: Pratik Butani,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-04-05 12:02:06

Existe una alternativa más fácil para cambiar el color de la barra de título, utilizando la biblioteca de soporte v7 appcompat proporcionada por Google.

Vea este enlace sobre cómo configurar esta biblioteca de soporte: https://developer.android.com/tools/support-library/setup.html

Una vez que haya hecho eso, es suficiente agregar las siguientes líneas a su res/values/styles.archivo xml:

<style name="AppTheme" parent="AppBaseTheme">
    <item name="android:actionBarStyle">@style/ActionBar</item>
</style>

<!-- Actionbar Theme -->
<style name="ActionBar" parent="Widget.AppCompat.Light.ActionBar.Solid.Inverse">
    <item name="android:background">@color/titlebackgroundcolor</item>
</style>

(asumiendo que "titlebackgroundcolor" está definido en su res/values/colors.XML, por ejemplo:

<color name="titlebackgroundcolor">#0000AA</color>

)

 1
Author: stefan.m,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-14 16:36:36

Las cosas parecen haber mejorado/más fácil desde Android 5.0 (nivel de API 21).

Creo que lo que estás buscando es algo como esto:

<style name="AppTheme" parent="AppBaseTheme">
    <!-- Top-top notification/status bar color: -->
    <!--<item name="colorPrimaryDark">#000000</item>-->
    <!-- App bar color: -->
    <item name="colorPrimary">#0000FF</item>
</style>

Ver aquí para referencia:

Https://developer.android.com/training/material/theme.html#ColorPalette

 1
Author: Loisaida Sam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-07 05:31:13