我一直在寻找如何让小部件的背景改变颜色我尝试放置一个适合活动的图标并改变它,但它没有用。我尝试创建一个可以改变它的服务,但这似乎过度杀戮而且对我没有用。有人说要改变它作为一个可绘制的。
所以这是我的代码, 主要活动
public class MainActivity extends AppWidgetProvider {
private static int layoutId;
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
RemoteViews updateViews;
for (int i = 0; i < appWidgetIds.length; i++) {
int appWidgetId = appWidgetIds[i];
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.activity_main);
layoutId = R.layout.activity_main;
Random rnd = new Random();
int bgcolor = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
//updating current widget
views.setInt(layoutId, "setBackgroundResource", R.color.colorPrimaryDark);
updateViews = new RemoteViews(context.getPackageName(),layoutId);
AppWidgetManager.getInstance(context).updateAppWidget(
new ComponentName(context, MainActivity.class), updateViews);
}
}
}
activity_main.xml中
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:background="@color/white"
tools:context="com.example.stephan.mywidget.MainActivity">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/bgcolor"
android:scaleType="fitXY"/>
</RelativeLayout>
AndroidManifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.stephan.mywidget">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<receiver android:name="MainActivity">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data android:name="android.appwidget.provider"
android:resource="@xml/widget"/>
</receiver>
</application>
</manifest>
色彩资源
<resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorAccent">#FF4081</color>
<color name="white">#FFFFFF</color>
</resources>
Widget.xml
<appwidget-provider
xmlns:android="http://schemas.android.com/apk/res/android"
android:minWidth="146dp"
android:minHeight="72dp"
android:updatePeriodMillis="28800000"
android:initialLayout="@layout/activity_main">
</appwidget-provider>
我实际上需要它来改变随机颜色,但它甚至不会改变一种颜色。我该如何改变它?