开发者

Widget ImageButton listener not allways called

开发者 https://www.devze.com 2023-03-01 05:43 出处:网络
I have a simple Widget (Android 2.1) containing just a LinearLayout, itself containing an ImageButton.

I have a simple Widget (Android 2.1) containing just a LinearLayout, itself containing an ImageButton. The ImageButton has a on-click listener. The problem is: If I put several of this same widget on my home screen, some are working (listener called when button pressed), and some are not! I cannot see any pattern in which are working and which are not.

Here is the widget layout:

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@null">

<ImageButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/ImageButton01"
    android:src="@drawable/widget_running"
    android:background="@null">
</ImageButton>

And here is the widget provi开发者_StackOverflow社区der code:

public class GPAppWidgetProvider extends AppWidgetProvider {
private String mTag = getClass().getSimpleName();

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

    // Perform this loop procedure for each App Widget that belongs to this
    // provider
    for (int i = 0; i < N; i++) {
        Log.e(mTag, "widget onUpdate one loop");
        int appWidgetId = appWidgetIds[i];

        // Create an Intent
        Intent intent = new Intent(context, GPService.class).setAction(ACTION_WIDGET_TOGGLE_PAUSE);
        intent.putExtra("widgetId", appWidgetId);
        PendingIntent pauseIntent = PendingIntent.getService(context, 0, intent, 0);

        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.gp_appwidget);
        views.setOnClickPendingIntent(R.id.ImageButton01, pauseIntent);

        // widget update
        appWidgetManager.updateAppWidget(appWidgetId, views);
    }
}

}


I had the same problem.

Don't forget to set a different "requestCode" when you call "getService" :

public static PendingIntent getService (Context context, int requestCode, Intent intent, int flags)

And make sure your "appWidgetId" is different for each widget.

0

精彩评论

暂无评论...
验证码 换一张
取 消