Android UI How to - Attach empty view for ListView for empty ListView adapter








The following code shows how to Attach empty view for ListView for empty ListView adapter.

Example

Layout xml file

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <LinearLayout
        android:id="@+id/myempty"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="No Items to Display"
        />
        <Button
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Tap Here to Refresh"
        />
    </LinearLayout>
    <ListView
        android:id="@+id/mylist"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
    />
</FrameLayout>

Main activity Java code

package com.java2s.myapplication3.app;
/*w w w .  ja  v  a2  s. co m*/
import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.ListView;


public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ListView list = (ListView)findViewById(R.id.mylist);
        LinearLayout empty = (LinearLayout)findViewById(R.id.myempty);

        list.setEmptyView(empty);

        //Continue adding adapters and data to the list
    }

}
null