Search code examples
androidandroid-gridviewandroid-appwidget

How to set a default text to app widget when there is no data?


I am using GridView in my app-widget. I want to set a default text to the app-widget when there is no data. I tried doing using getLoadingView() method but it's not working.

getLoadingViewMethod() of WidgetViewsFactory.java:

@Override
public RemoteViews getLoadingView() {

    Log.e("textview is displayed","true");
    RemoteViews row = new RemoteViews(mContext.getPackageName(), R.layout.widget_default_display);
    row.setTextViewText(R.id.txt_default_widget,"DEFAULT TEXT");
    return row;
}    

widget_default_display.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="180dp">

    <TextView
        android:id="@+id/txt_default_widget"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/no_notifications"
        android:textColor="@color/txt_sub_title_gray"
        android:textSize="@dimen/txt_title_size"/>

</LinearLayout>

Please suggest me some solution.


Solution

  • An AdapterView in an App Widget is used very similarly to one in your app's local layout. To display a certain View when the AdapterView's collection is empty, you need to set that View as the empty View on the AdapterView.

    For a Widget, the RemoteViews class has the setEmptyView() method for this. You'd use this method in your AppWidgetProvider, after creating the main RemoteViews object from the layout that contains your GridView. For example:

    RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
    ...
    
    rv.setEmptyView(R.id.grid_view, R.id.txt_default_widget);
    

    Please note that the empty View - the txt_default_widget TextView, in this case - must be in the same main layout as the GridView, rather than in the item layout.