android - 单击小部件上的按钮时更改布局

标签 android android-layout android-widget android-pendingintent remoteview

我有一个小部件。我想要做的是在单击按钮时更改布局。

这就是我正在做的:

public class MainWidgetProvider extends AppWidgetProvider {

    public static String ACTION_MENU_CLICKED = "MenuClicked";

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

        Intent intent = new Intent(context, MainWidgetProvider.class);
        intent.setAction(ACTION_MENU_CLICKED);

        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.main_widget_layout);

        views.setOnClickPendingIntent(R.id.button2, pendingIntent);
    }


    @Override
    public void onReceive(Context context, Intent intent) {
        super.onReceive(context, intent);

        if (intent.getAction().equals(ACTION_MENU_CLICKED)) {
            AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);

            RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.main_widget_layout);

            views.setViewVisibility(R.id.layout1,View.INVISIBLE);
            views.setViewVisibility(R.id.layout2,View.VISIBLE);

            final int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
            appWidgetManager.updateAppWidget(appWidgetId, views);

        }
    }
}

我的问题在哪里?现在的代码什么都不做。

最佳答案

在您的 onUpdate 中像这样更新您的代码-

PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.main_widget_layout);

        views.setOnClickPendingIntent(R.id.button2, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetIds, views);//you are missing this line.

并在您的 onReceive 方法中将 appWidgetId 替换为-

int[] appWidgetId = AppWidgetManager.getInstance(context).getAppWidgetIds(
            new ComponentName(context, MainWidgetProvider.class));

关于android - 单击小部件上的按钮时更改布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19998860/

相关文章:

SD 卡中的 Android Widget

android - Android 2.3.3 上的 Toast 小部件

android - seeking时如何隐藏SeekBar的tickmark?

php - 从 APK 获取应用名称

android - 如何在 VrPanoramaView 中动态移动图像

android - 最小宽度限定符不适用于 Android Studio

Android - 将类型对象添加到微调器小部件

android - picasso :将图像加载到小部件 ListView

android - 无法正确地将我的 LinearLayout 更改为 ListView

android - 从 SD 卡上的 XML 文件读取时出现问题