Android主屏幕小部件无法更新

时间:2016-10-10 20:03:03

标签: android android-studio android-widget

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

这是我的Widget类:

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的更改外,一切正常。有什么问题?

1 个答案:

答案 0 :(得分:2)

首先设置新文本:

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

然后让AppWidgetManager更新小部件:

appWidgetManager.updateAppWidget(watchWidget, remoteViews);
相关问题