I am creating a widget for Android but I'm facing an issue. I have a container in my main widget layout, and I want to add it new line in the list dynamically. For that, I use the addView methods on the RemoteViews of my container:
Widget.java
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
for (int i = 0; i < 10; i++) {
RemoteViews rowView = new RemoteViews(context.getPackageName(), R.layout.row);
views.addView(R.id.list_container, rowView);
}
row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="@+id/row"
android:layout_width="match_parent"
android:layout_height="20dp"
android:orientation="horizontal"
xmlns:android="http://schemas.android.com/apk/res/android">
</LinearLayout>
widget.xml
...
<LinearLayout
android:id="@+id/list_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout>
...
So now, I have a Layout with 10 lines/copy of my row layout. But each line has the same id depending of the one i put in my layout/row.xml.
I want now to delete a row, how can I do this because all row have the same id ?
I can't change the id of my row because RemoteViews doesn't seem to accept the setId(id) method
Remove all views not working as I expected :
views.removeAllViews(R.id.row);
Anyone with and idea of how this works ? Maybe I'm doing this the wrong way or widget layout are not made to be programmatically defined ?
I am adding this answer because Mike M found the solution. Mike. M Comment
Don't know if it's the better way of doing this but its works
I save RemoteViews of my rows in an Array. Each time I update the widget I fill the view with the RemoteViews of my array. Recreating all the layout tree of my list.
Before each update, I can now remove or add row to my ArrayList which will display what I want.
ArrayList<RemoteViews> rows = new ArrayList();
// Adding rows : rows.size() = 3
for (int i = 0; i < 3; i++) {
RemoteViews rowView = new RemoteViews(context.getPackageName(), R.layout.row);
rows.add(rowView);
}
// Removing a row : rows.size() = 2
rows.remove(2);
// Update the Layout
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
views.removeAllViews(R.id.list_container)
for (int i = 0; i < rows.size(); i++) {
views.addView(R.id.list_container, rowView);
}
// Only 2 rows appear
Another problem was to acces specific Element in my row, but this can be done usin the same method. RemoteViews.settextviewtext(id) only search the id in their childen so I can acces to element in the rows because they have distinct id in it.