【发布时间】:2018-11-01 21:42:21
【问题描述】:
我想在单击时更改一个布尔变量值和小部件的背景? 这是小部件 xml 文件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f15"
android:padding="@dimen/widget_margin"
android:id="@+id/appwidget_layout">
<TextView
android:id="@+id/appwidget_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_margin="8dp"
android:textColor="#ffffff"
android:textSize="24sp"
android:textStyle="bold|italic" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/appwidget_button"/>
这里是小部件 java 活动
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
for (int appWidgetId : appWidgetIds) {
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.example_app_widget_provider);
Intent intent = new Intent(context, ExampleAppWidgetProvider.class);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
PendingIntent buttonPendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
views.setOnClickPendingIntent(R.id.appwidget_button, buttonPendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
public boolean buttonState = false;
@Override
public void onReceive(Context context, Intent intent) {
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.example_app_widget_provider);
if (intent.getAction()!= null) {
Bundle extras = intent.getExtras();
if (buttonState) {
buttonState = false;
views.setInt(R.id.appwidget_layout, "setBackgroundColor", Color.GREEN);
views.setInt(R.id.appwidget_text, "setBackgroundColor", Color.GREEN);
Toast.makeText(context, "Clicked!!", Toast.LENGTH_SHORT).show();
} else {
buttonState = true;
views.setInt(R.id.appwidget_layout, "setBackgroundColor", Color.RED);
views.setInt(R.id.appwidget_text, "setBackgroundColor", Color.RED);
Toast.makeText(context, "Clicked!!", Toast.LENGTH_SHORT).show();
}
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
appWidgetManager.updateAppWidget(new ComponentName(context, ExampleAppWidgetProvider.class),
views);
}
}
}
代码运行时,onRecieve方法中的部分没有被执行。我想知道如何接收来自发送意图的同一个小部件的点击,以便我可以修改它。
提前致谢
【问题讨论】:
标签: android widget android-widget android-appwidget