处理Widget ListView中的项目点击[Android]

时间:2016-09-21 08:40:27

标签: android listview widget

我现在已经搜索了几个星期,但我无法找到答案。我试图在ListView内创建widget。我设法填充了ListView。我的问题是当我点击ListView中的某个项目时,我想打开Activity并将该项目的Id传递给我调用的Activity。但是,当我转到Id时,我似乎无法正确地通过null传递Activity

这是我的代码

WidgetProvier

public class WidgetProvider extends AppWidgetProvider {
 public void onUpdate(Context context, AppWidgetManager appWidgetManager,
                     int[] appWidgetIds) {
....
  for (int i = 0; i < N; ++i) {
        RemoteViews remoteViews = updateWidgetListView(context,
                appWidgetIds[i]);


        appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds[i], R.id.listViewWidget);
        appWidgetManager.updateAppWidget(appWidgetIds[i], remoteViews);
    }

    super.onUpdate(context, appWidgetManager, appWidgetIds);
}

  private RemoteViews updateWidgetListView(Context context, int appWidgetId) {
  //For ListView
  Intent svcIntent = new Intent(context, WidgetService.class);
  svcIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
  svcIntent.setData(Uri.parse(svcIntent.toUri(Intent.URI_INTENT_SCHEME)));
 remoteViews.setRemoteAdapter(appWidgetId, R.id.listViewWidget, svcIntent);
    //When item is clicked on ListView
    Intent startActivityIntent = new Intent(context, ActivityOne.class);
    PendingIntent startActivityPendingIntent = PendingIntent.getActivity(context, 0, startActivityIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    remoteViews.setPendingIntentTemplate(R.id.listViewWidget, startActivityPendingIntent); 

 return remoteViews;
}

WidgetService

public class WidgetService extends RemoteViewsService {

@Override
public RemoteViewsFactory onGetViewFactory(Intent intent) {
    return (new ListProvider(this.getApplicationContext(), intent));
}
}

ListProvider

 @Override
 public RemoteViews getViewAt(int position) {
 final RemoteViews widgetRow = new RemoteViews(
        context.getPackageName(), R.layout.list_row);

ListItem listItem = listItemList.get(position);
widgetRow.setTextViewText(R.id.txtID, listItem.id);

//Pass the ID to ActivityOne 
Intent fillInIntent = new Intent();
fillInIntent.putExtra("EXTRA_ID", listItem.id);
widgetRow.setOnClickFillInIntent(R.id.llRow, fillInIntent);

return widgetRow;
}

ActivityOne

public class ActivityOne extends Activity {
  String mID;

 @Override
protected void onCreate(Bundle savedState) {

....
 mID = intent.getStringExtra("EXTRA_ID");
....
}

我使用ListView内的Web Service填充ListProvider并在onDataSetChanged上调用List。在调试它时,在填充EXTRA_ID的同时,它还会将所有数据放在Activity中,也许这就是为什么在打开textField.clearButtonMode = UITextFieldViewMode.whileEditing; 时会混淆并返回null的原因,我不知道为什么要解决这个问题。请指导我如何解决这个问题。提前感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

我发现了一个很棒的example我尝试了它,并更改了数据的设置方式,然后更改了我onReceive中的AppWidgetProvider我在那里调用ActivityOne并通过了来自Bundle的数据。此link也可以帮助我在Activity内的onReceive内启动AppWidgetProvider。我只是在主屏幕上删除小部件时遇到应用程序崩溃。当我发现如何解决它时,会更新这个答案。

编辑

我必须解决崩溃部分,我忘记添加onDelete,然后添加notifyAppWidgetViewDataChanged以及ListView现在正常工作。