I am trying to create a homescreen widget using the 3.1 SDK. I followed the StackWidget tutorial. and changed the StackView
to ListView
.
I want to add an image and text to each row in my list, and these are loaded at runtime.
I use this code in my WidgetProvider.java
class
public RemoteViews getViewAt(int position) {
Bitmap bitmap = ((BitmapDrawable)mWidgetItems.get(position).getImage());
RemoteViews image = new RemoteViews(mContext.getPackageName(), R.layout.widget_item);
image.setImageViewBitmap(R.id.widget_image, bitmap );
RemoteViews text = new RemoteViews(mContext.getPackageName(), R.layout.widget_item);
text.setTextViewText(R.id.widget_text, mWidgetItems.get(position).getText());
RemoteViews layout = new RemoteViews(mContext.getPackageName(), R.layout.widget_item);
Bundle extras = new Bundle();
extras.putInt(StackWidgetProvider.EXTRA_ITEM, position);
Intent fillInIntent = new Intent();
fillInIntent.putExtras(extras);
layout.setOnClickFillInIntent(R.id.widget_item, fillInIntent);
return layout;
}
All of this works correctly when I use StackView
, but changing to ListView
messes up everything. The result is this
Only one view can be returned. So, if I add the following code, this problem occurs, if I don't add it, then the content of the list is empty.
layout.addView(R.id.widget_item, image);
layout.addView(R.id.widget_item, text);
How else do I add multple views to a widget? Why does this work for StackView but not ListView? and how do I rectify this?
Any help is greatly appreciated.
EDIT
widget_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/widget_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_vertical">
<ImageView
android:id="@+id/widget_image"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"/>
<TextView
android:id="@+id/widget_text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="20dp"
android:layout_weight="1"
android:textColor="#000000"/>
</LinearLayout>
You rectify this by inflating the right layout from the outset. R.layout.widget_image
should already have whatever stuff you have in R.layout.widget_image
and R.layout.widget_item
.
This will be:
And, as an extra bonus, it should work for any supported AdapterView
-based app widget.