gpt4 book ai didi

Android 主屏幕小部件未更新

转载 作者:行者123 更新时间:2023-11-29 19:30:54 26 4
gpt4 key购买 nike

我创建了一个简单的主屏幕小部件,用于显示从数据库生成的名称。我添加了一个按钮来刷新 TextView 中的名称,但问题是小部件没有更新。

这是我的小部件类:

public class QuotesWidgets extends AppWidgetProvider {
ComponentName watchWidget;
RemoteViews remoteViews;
private static final String SYNC_CLICKED = "automaticWidgetSyncButtonClick";
void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
int appWidgetId) {

Realm mRealm;

mRealm=Realm.getDefaultInstance();
Random random = new Random();
RealmResults<names> randomName = mRealm.where(Names.class).findAll();
Names name = randomName.get(random.nextInt(randomName.size()));
String name1 = quote.getName();
remoteViews = new RemoteViews(context.getPackageName(), R.layout.my_widget);
watchWidget = new ComponentName(context, MyWidget.class);
remoteViews.setTextViewText(R.id.textview, name);

remoteViews.setOnClickPendingIntent(R.id.refresh, getPendingSelfIntent(context, SYNC_CLICKED));
appWidgetManager.updateAppWidget(watchWidget, remoteViews);
}

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// There may be multiple widgets active, so update all of them
for (int appWidgetId : appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId);
}
}

@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if (SYNC_CLICKED.equals(intent.getAction())) {
Realm mRealm;
mRealm=Realm.getDefaultInstance();

AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
remoteViews = new RemoteViews(context.getPackageName(), R.layout.quotes_widgets);
watchWidget = new ComponentName(context, MyWidgets.class);
appWidgetManager.updateAppWidget(watchWidget, remoteViews);
Random random = new Random();
RealmResults<names> randomName = mRealm.where(Names.class).findAll();
Names name = randomName.get(random.nextInt(randomName.size()));
String name1 = quote.getName();

Toast.makeText(context,name1, Toast.LENGTH_SHORT).show();
remoteViews.setTextViewText(R.id.textview, name1);


}
}
protected PendingIntent getPendingSelfIntent(Context context, String action) {
Intent intent = new Intent(context, getClass());
intent.setAction(action);
return PendingIntent.getBroadcast(context, 0, intent, 0);
}
}

我在示例中使用了 Toast 消息,当我单击按钮时,Toast 消息每次都以不同的名称出现,所以除了小部件中 TextView 的更改外,一切都运行良好。有什么问题?

最佳答案

首先设置新文本:

 remoteViews.setTextViewText(R.id.textview, name1);

然后让 AppWidgetManager 更新小部件:

appWidgetManager.updateAppWidget(watchWidget, remoteViews);

关于Android 主屏幕小部件未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39965917/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com