为我的小部件设置动态背景时遇到了问题:
我的首选项返回用户选择的颜色,我想将其应用于小部件,但具有渐变效果。所以这就是我现在所处的位置:
我的widget.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/widget_layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/style_widget"
> ...我的Service.java:
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
remoteViews = new RemoteViews(this.getPackageName(), R.layout.widget);
this.prefs = PreferenceManager.getDefaultSharedPreferences(this);
//this is where I get the color preference value, and create another with some transparency
int color1 = prefs.getInt("background_color", 00000000);
int color2 = Color.argb(22, Color.red(color1), Color.green(color1), Color.blue(color1));
int colors[] = { color1, color2 };
//Create the GradientDrawable:
GradientDrawable gradientDrawable = new GradientDrawable(
GradientDrawable.Orientation.TOP_BOTTOM, colors);如果我这样做了:
remoteViews.setInt(R.id.widget_layout, "setBackgroundColor", color1);我更改了背景颜色,但由于gradientDrawable不是一个整数,如何通过remoteViews将其应用于我的背景?
发布于 2014-01-16 04:11:52
好吧,我在这里找到了答案:
Setting GradientDrawable through RemoteView
我创建了一个填充整个小部件的图像视图,然后使用我的gradientDrawable创建了一个位图,然后将该位图设置为图像视图:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/widget_layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/style_widget"
android:padding="0dip" >
<ImageView
android:id="@+id/bck_image"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="fitXY"
/>然后在我的服务中:
GradientDrawable gradientDrawable = new GradientDrawable(
GradientDrawable.Orientation.LEFT_RIGHT, colors);
float dpi = getBaseContext().getResources().getDisplayMetrics().xdpi;
float dp = getBaseContext().getResources().getDisplayMetrics().density;
Bitmap bitmap = Bitmap.createBitmap(Math.round(288 * dp), Math.round(72 * dp), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
gradientDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
gradientDrawable.setCornerRadius(5 * (dpi/160));
gradientDrawable.draw(canvas);
remoteViews.setImageViewBitmap(R.id.bck_image, bitmap);(我对Android非常陌生,所以我不知道代码是否格式良好,但对我来说,它可以工作,以防它能帮助任何人。)
https://stackoverflow.com/questions/21095025
复制相似问题