Thursday, May 30, 2013

Android: Mostrar un mensaje cuando el ListView está vacío

Si se está usando el ListView, existe un método que se llama setEmptyView el cual recibe un view y se muestra cuando la lista está vacía. Aquí un ejemplo:

Primero se debe agregar un View (como un botón o un texto) al Layout de la actividad donde tienen el ListView. Aquí un ejemplo con un texto:

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

    <ListView
        android:id="@+id/myListView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>
    <TextView
        android:id="@+id/emptyListView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="gone"
        android:text="@string/emptyList" >
    </TextView>

</LinearLayout>
Es importante que tenga el atributo android:visibility="gone" para que no se muestre cuando la lista si tenga contenido.

Luego en la clase donde utlizan el ListView, deberán llamar al método setEmptyView y entregarle el TextView que creamos en el xml

ListView lv = getListView();
lv.setEmptyView(findViewById(R.id.emptyListView));
o bien

ListView lv = (ListView)findViewById(R.id.myListView);
lv.setEmptyView(findViewById(R.id.emptyListView));


Bookmark and Share

No comments:

Related Posts Plugin for WordPress, Blogger...