¿Cómo cambiar el color de la línea de separación Android ListView?


400

Quiero cambiar el color de la ListViewlínea de separación. Cualquier ayuda sería apreciada.

Respuestas:


765

Puede establecer este valor en un archivo xml de diseño usando android:divider="#FF0000". Si está cambiando el color / dibujable, también debe establecer / restablecer la altura del divisor.

<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content">

  <ListView 
    android:id="@+id/android:list"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:divider="#FFCC00"
    android:dividerHeight="4px"/>

</LinearLayout>

11
También debe poder especificar un Drawablerecurso en android:divider. El divisor existente es un gradiente.
— CommonsWare

6262
Si lo hace en XML, asegúrese de ver la altura también usando android: dividerHeight, de lo contrario no obtendrá línea
— Eric Novins

8
Según mi experiencia, lea "debería restablecer la altura del divisor" a "debe establecer la altura del divisor"
— dpjanes

44
No recomendaría usar la pxunidad para definir tamaños en Android, use dpen su lugar
— Marek Sebera

12
Parece que podría haber una buena razón para usar px en este caso específico. Ver: stackoverflow.com/a/12061612/10505
— greg7gkb

163

O puedes codificarlo:

int[] colors = {0, 0xFFFF0000, 0}; // red for the example
myList.setDivider(new GradientDrawable(Orientation.RIGHT_LEFT, colors));
myList.setDividerHeight(1);

Espero eso ayude


¡Perfecto, mis artículos estaban sobre un fondo degradado rojizo y su efecto los hizo magníficos!
— Darkendorf

1
si extiende ListActivity, reemplace mylist con getListView ()
— Aziz

87

Para una sola línea de color use:

list.setDivider(new ColorDrawable(0x99F10529));   //0xAARRGGBB
list.setDividerHeight(1);

Es importante que DividerHeight se configure después del divisor , de lo contrario no obtendrá nada.


1
Gracias, llamé a setDividerHeight () antes de setDivider () y no se mostró ningún divisor.
— Andreas Klöber

3
Comentario muy útil sobre el orden de las operaciones. Acabo de pasar 2 horas tratando de que funcione. Bonito diseño, Android.
— Nick Frolov

12

También puede obtener los colores de sus recursos utilizando:

dateView.setDivider(new ColorDrawable(_context.getResources().getColor(R.color.textlight)));
dateView.setDividerHeight(1);

10

Versión XML para el efecto genial de @Asher Aslan.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >

    <gradient
        android:angle="180"
        android:startColor="#00000000"
        android:centerColor="#FFFF0000"
        android:endColor="#00000000"/>

</shape>

Nombre para esa forma como: list_driver.xml bajo carpeta dibujable

<ListView
        android:id="@+id/category_list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" 
        android:divider="@drawable/list_driver"
        android:dividerHeight="5sp" />

6

Hay dos formas de hacer lo mismo:

  1. Puede establecer el valor de android: divider = "# FFCCFF" en el archivo xml de diseño. Con esto también debe especificar la altura del divisor como este android: dividerHeight = "5px ".

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    
      <ListView 
      android:id="@+id/lvMyList"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:divider="#FFCCFF"
      android:dividerHeight="5px"/>
    
    </LinearLayout>
    
  2. También puede hacer esto programáticamente ...

    ListView listView = getListView();
    ColorDrawable myColor = new ColorDrawable(
        this.getResources().getColor(R.color.myColor)
    );
    listView.setDivider(myColor);
    listView.setDividerHeight();
    

2

Use el siguiente código en su archivo xml

<ListView 
    android:id="@+id/listView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:divider="#000000" 
    android:dividerHeight="1dp">
</ListView> 

2
Es mejor explicar un poco sobre por qué funciona su solución. Las respuestas de solo código pueden solucionar el problema, pero eso no necesariamente responde a la pregunta del autor de la pregunta.
— SuperBiasedMan

1

utilizando programáticamente

           // Set ListView divider color
            lv.setDivider(new ColorDrawable(Color.parseColor("#FF4A4D93")));

            // set ListView divider height
            lv.setDividerHeight(2);

usando xml

<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content">

  <ListView 
    android:id="@+id/android:list"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:divider="#44CC00"
    android:dividerHeight="4px"/>

</LinearLayout>

0

Utilice android:divider="#FF0000"y android:dividerHeight="2px"para ListView.

<ListView 
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:divider="#0099FF"
android:dividerHeight="2px"/>
Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.