10

I have an app widget and I'd like to add Views (TextView, etc.,) to the RemoteView but it never shows up.
Here goes the code:

RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
RemoteViews newView = new RemoteViews(context.getPackageName(), R.layout.widget_row_layout);
    newView.setTextViewText(R.id.textUser, "1234");
    views.addView(views.getLayoutId(), newView);
// Tell the AppWidgetManager to perform an update on the current App Widget
appWidgetManager.updateAppWidget(appWidgetId, views);

Any ideas?


This is what I ended up doing:

RemoteViews newView = new RemoteViews(context.getPackageName(), R.layout.widget_row_layout);
    newView.setTextViewText(R.id.textUser, "1234");
ComponentName thisWidget = new ComponentName(this,WidgetProvider.class);
AppWidgetManager manager = AppWidgetManager.getInstance(this);
    manager.updateAppWidget(thisWidget, newView);
OlivierM
  • 2,820
  • 24
  • 41
Tony G.
  • 220
  • 1
  • 3
  • 11
  • 1
    You should either add your solution as an answer and mark it as such or select an existing answer as the solution. Otherwise this is just hanging out there as unanswered... – Ross Hambrick Nov 27 '10 at 23:48

1 Answers1

30

The addView() method needs the id of the view inside the layout you want to add this new view to, not the layout itself.

Instead of this:

views.addView(views.getLayoutId(), newView);

Try this:

views.addView(R.id.view_container, newView);

Assuming your layout looks something like this:

file: layout/widget_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
    <LinearLayout
        android:id="@+id/view_container"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
        <!-- New views will be added here at runtime -->
    </LinearLayout>
</LinearLayout>
Ross Hambrick
  • 5,880
  • 2
  • 43
  • 34
  • This is what I ended up doing: – Tony G. Nov 21 '10 at 14:33
  • Great ! This is exactly what I needed. Thanks a lot hambonious. – Hubert May 20 '11 at 04:07
  • 1
    +1, Fiiiinally an explanation for RemoteView.addView()... Also, I found out that you can add the ID to the outer LinearLayout and not need a second one. – Izkata Jan 22 '12 at 03:58
  • 2
    @Izkata That is correct. I only laid it out this way since I assumed you would be adding to a specific container within the overall layout. But that is definitely not a requirement. – Ross Hambrick Jan 31 '12 at 21:13
  • @hambonious I'm upping your comment because I ended up nesting them anyway, for better control over padding/gravity/etc ;) – Izkata Jan 31 '12 at 21:28