views:

603

answers:

1

How do I add a View dynamically in an android widget?

I realize that the RemoteViews works as a container of updates, but the RemoteViews.addView is only available on API level 7 (and I want my widget to work on HTC Hero phones, which has API level 3).

A: 

In your AppWidgetProvider, when you create your RemoteViews instance to do an update, you pass in a layout ID to the constructor. If you want your app widget to have different contents, pass in a different layout ID.

CommonsWare
Ah, I've tried that, this is what I stumble across:I create my LinearLayout, add the Views I want, do myLinearLayout.setId(123456); and then pass myLinearLayout.getId() to the constuructor of RemoteViews.Then I get the following error:/ResourceType( 610): No package identifier when getting value for resource number 0x0001e240W/AppWidgetHostView( 610): updateAppWidget couldn't find any view, using error viewW/AppWidgetHostView( 610): android.content.res.Resources$NotFoundException: Resource ID #0x1e240W/AppWidgetHostView( 610):
aioobe
You have to use layout XML for the `RemoteViews` constructor. That is kinda the point -- the home screen process can access your layout resources but cannot access your in-RAM View objects. So, if you have multiple layouts you want to use with your app widget, have multiple layout XML files, and choose the one that fits the need for a particular update. You can use `<include>` and `<merge>` elements in the XML to minimize duplication, if needed.
CommonsWare
So your'e basically saying that it is impossible on API level 3? (I suppose it is possible on API level 7, since there is an addView method in RemoteViews).
aioobe
There is no functional difference between "adding a View" to an existing app widget and inflating a new layout with the additional `View` as part of the layout. Since even `addView()`, in the end, requires layouts, you are going to have to deal with layout XML, on any API level. So, if your real question is "how can I add a View to an app widget where I construct the View in Java code", the answer is "it is impossible". If the real question is "I have an app widget that looks like X and now I want it to look like Y", use and choose layouts for X and Y.
CommonsWare