简体   繁体   中英

ListView and Button Click in Widget [Android]

I created a Widget that has a Button and below it has a ListView . When button is clicked I wanted to open an Activity but it seems not working I don't know why.

Here is my code in my AppWidgetProvider

 @Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
                     int[] appWidgetIds) {
    final int N = appWidgetIds.length;

    for (int i = 0; i < N; ++i) {
        RemoteViews remoteViews = updateWidgetListView(context,
                appWidgetIds[i]);
        appWidgetManager.updateAppWidget(appWidgetIds[i], remoteViews);


    Intent configIntent = new Intent(context, NewActivity.class);
    PendingIntent configPendingIntent = PendingIntent.getActivity(context, 0, configIntent, 0);
    remoteViews.setOnClickPendingIntent(R.id.btn_activity, configPendingIntent);
    }



    super.onUpdate(context, appWidgetManager, appWidgetIds);

} 

private RemoteViews updateWidgetListView(Context context, int appWidgetId) {

    RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
            R.layout.widget_layout);

    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);

    remoteViews.setEmptyView(R.id.listViewWidget, R.id.empty_view);

    return remoteViews;
}

I'm thinking it is because of my updateWidgetListView , I tried putting the Intent inside updateWidgetListView but it still doesn't work when button is clicked.

Thank you in advance.

On my onUpdate I initialize my widget_layout before the iteration

public void onUpdate(Context context, AppWidgetManager appWidgetManager,
                     int[] appWidgetIds) {

    // initializing widget layout
    RemoteViews rvBtn = new RemoteViews(context.getPackageName(),
            R.layout.home_widget);

    // register the button event
    rvBtn.setOnClickPendingIntent(R.id. btn_activity,
            buildButtonPendingIntent(context));

    final int N = appWidgetIds.length;

    for (int i = 0; i < N; ++i) {
     //initialize another RemoteViews for ListView
        RemoteViews remoteViews = updateWidgetListView(context,
                appWidgetIds[i]);
        appWidgetManager.updateAppWidget(appWidgetIds[i], remoteViews);
    }


    super.onUpdate(context, appWidgetManager, appWidgetIds);

}

Then create a BroadcastReceiver where I will call the Intent and add that receiver on my AndroidManifest .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM