我有一个小部件,包含1个图像视图和1个文本视图。
![on](https://istack.dev59.com/fUobf.webp)
我希望在单击时更改图像。 请注意,以下代码无法捕获触摸事件。
![on](https://istack.dev59.com/fUobf.webp)
![off](https://istack.dev59.com/XkazY.webp)
package com.sigrlami.rixvpn.widget;
import java.util.Random;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.RemoteViews;
import com.sigrlami.rixvpn.R;
public class VpnWidgetProvider extends AppWidgetProvider {
private boolean currentStatus = false;
// log tag
private static final String LOG = "com.sigrlami.rixvpn.widget.VpnWidgetProvider";
//public static final String CLICK = "com.sigrlami.rixvpn.CLICK";
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// Get all ids
ComponentName thisWidget = new ComponentName(context, VpnWidgetProvider.class);
int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
for (int widgetId : allWidgetIds) {
// Create some random data
int number = (new Random().nextInt(100));
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.vpn_widget);
Log.w("WidgetExample", String.valueOf(number));
// Set the text
remoteViews.setTextViewText(R.id.layout_vpn_widget_tv_Check, String.valueOf(number));
// Register an onClickListener
Intent intent = new Intent(context, VpnWidgetProvider.class);
intent.setAction(appWidgetManager.ACTION_APPWIDGET_UPDATE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
remoteViews.setOnClickPendingIntent(R.id.layout_vpn_widget_iv_Check, pendingIntent);
if (currentStatus = false) {
remoteViews.setImageViewResource(R.id.layout_vpn_widget_iv_Check, R.drawable.on);
} else {
remoteViews.setImageViewResource(R.id.layout_vpn_widget_iv_Check, R.drawable.off);
}
appWidgetManager.updateAppWidget(widgetId, remoteViews);
}
}
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) {
if (currentStatus == false) {
currentStatus = true;
} else {
currentStatus = false;
}
}
super.onReceive(context, intent);
}
通过调试器查看此部分时,没有发现任何奇怪的地方,但当我将其更改为getActivity()时,它显示我正在尝试启动一个不存在的活动。我知道发生了一些事情,但这对我来说是无用的。
// Register an onClickListener
Intent intent = new Intent(context, VpnWidgetProvider.class);
intent.setAction(appWidgetManager.ACTION_APPWIDGET_UPDATE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
remoteViews.setOnClickPendingIntent(R.id.layout_vpn_widget_iv_Check, pendingIntent);
但是当应用部署到设备上时,它只能运行1次。 有什么建议我做错了什么吗?