Páginas

Texto alternativo para listas vacías
Alternative text for empty lists

La clase ListView de Android ofrece el método setEmptyView, que permite mostrar un mensaje al usuario si una lista está vacía. Para utilizarlo, es necesario definir en el layout de la página un elemento con visibilidad gone, que será el que se le pase a dicho método.

Como ejemplo podemos ver cómo se ha implementado la lista de jugadores de Memory Battle. Este es el fragmento del fichero de layout.

    <ListView
        android:id="@+id/players_list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" /> 

    <TextView
        android:id="@+id/no_players_text"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/playersList"
        android:text="@string/no_players"
        android:visibility="gone" />

Y este el código que indica a la lista que debe usar el TextView como vista a mostrar cuando no tiene elementos.

playersList = (ListView) findViewById(R.id.playersList);
playersList.setEmptyView(findViewById(R.id.no_players_text));

Dado que lo que espera setEmptyView es un objeto View, se podría cambiar el texto por cualquier otro componente, como una imagen.
ListView class in Android provides setEmptyView method, which allows us to show a message to the user if the list is empty. To use it, we have to define in the layout file an element with gone visibility. That will be the parameter for setEmptyView.

This example shows how I´ve implemented the players list on Memory Battle. This is the fragment in the layout file:

    <ListView
        android:id="@+id/players_list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" /> 

    <TextView
        android:id="@+id/no_players_text"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/playersList"
        android:text="@string/no_players"
        android:visibility="gone" />

And this is the code to tell the list that it has to show the TextView when it has no elements.

playersList = (ListView) findViewById(R.id.playersList);
playersList.setEmptyView(findViewById(R.id.no_players_text));

You can use any View object as parameter for setEmptyView, so you could change the text for an image, for example.

No hay comentarios:

Publicar un comentario