问题
I've this homescreen widget:
It's easy to update for example two buttons next to the logo from activity, because I have their appWidgetIds from onUpdate method from AppWidgetProvider, but imagebuttons in the list are created in RemoteViewsFactory class in getViewAt() method.
@Override
public RemoteViews getViewAt(int position) {
RemoteViews row = new RemoteViews(ctxt.getPackageName(), R.layout.list_row_widget);
row.setTextViewText(R.id.tvDescription, items.get(position).name);
Intent i = new Intent();
Bundle extras = new Bundle();
extras.putBoolean(TimeWidgetProvider.ACTION_WORK_START, true);
extras.putInt(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
i.putExtras(extras);
row.setOnClickFillInIntent(R.id.btnStartWork, i);
return (row);
}
so every of them have same id (R.id.btnStartWork), and same appWidgetId which is not the row id but the whole widget id.
I need to change imagebutton in the row which I have clicked on, but because I've only one appwidget id in Activity and its for whole widget, everytime I use:
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getBaseContext());
RemoteViews views = new RemoteViews(getBaseContext().getPackageName(), R.layout.widget_layout);
views.setImageViewResource(R.id.btnStartWork, R.drawable.button_active);
appWidgetManager.updateAppWidget(mAppWidgetId, views);
It changes the first imagebutton not the selected one.
I have tried to pass remoteviews row from factory, but it didn't work because when I called
appWidgetManager.updateAppWidget(mAppWidgetId, row);
with the id of whole widget, widget was gone and only the selected row was visible. I can get the position of item in list, but it's not helpful because it's not a viewId. I have read many tutorial including this: http://developer.android.com/guide/topics/appwidgets/index.html
But still haven't found the answer, It's my first widget. Help please.
Thanks ;)
回答1:
Actually the solution was quite simple, in getViewAt() method save the position of every imagebutton to extras:
extras.putInt(TimeWidgetProvider.POSITION, position);
then in handling method store somewhere the index of selected item
TimeWidgetProvider.selected = extras.getInt(TimeWidgetProvider.POSITION);
and after that, use this:
appWidgetManager.notifyAppWidgetViewDataChanged(mAppWidgetId, R.id.list);
at last again in the getViewAt() method change imagebutton on index which you have previously stored.
if (position == TimeWidgetProvider.selected) {
row.setImageViewResource(R.id.btnStartWork, R.drawable.button_active);
} else {
row.setImageViewResource(R.id.btnStartWork, R.drawable.button_inactive);
}
The whole list is refreshed with changed states of selected items.
Thx Tamás Müller for this solution.
来源:https://stackoverflow.com/questions/22373858/android-appwidget-listview-change-selected-imagebutton-onclick