Search code examples
androidandroid-listfragmentempty-list

How to dynamically change text of empty view in listfragment


I have red many solutions regarding this but none of them solved my problem. What i want to do is, when my list view is empty its ok if the default empty text view shows up (which is declared in xml) but what if i want to change its text at some point in an activity that extends listfragment according to my need and make it visible.... Recently i tried this:

public void setEmptyText(CharSequence emptyText) {
    ListView mListView = (ListView) NotificationsView.findViewById(android.R.id.list);
    View emptyView = mListView.getEmptyView();
        ((TextView) emptyView).setText(emptyText);
}

It doesn't give any error but it is not solving the problem too. Any Help would be appreciated thanks

EDIT: here is my layout of listfragment

     <?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:ignore="MergeRootFrame" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_vertical|center_horizontal"
        android:orientation="vertical" >

        <ListView
            android:id="@id/android:list"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/fragment_bg"
            android:divider="@null"
            android:dividerHeight="1dp"
            android:listSelector="@drawable/list_style" >
        </ListView>

        <TextView
            android:id="@id/android:empty"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/fragment_bg"
            android:text="No data" />
    </LinearLayout>

</android.support.v4.widget.SwipeRefreshLayout>

Solution

  • If you are using ListFragment all you need to do is call the method

    setEmptyText("Your empty text"):
    

    The system will recognize the view label with the android:id="@id/android:empty" id and will change the text for you. No need to reference it or do any cast, it's all built in the ListFragment