2012-09-17 35 views
2

以下是我想要做的事情:我有一个小部件,并且我想根据用户对颜色的选择设置其背景。它必须是一个渐变。背景是通过设置linearLayout的背景来设置的。为了测试,我做了一个假的背景为:通过RemoteView设置GradientDrawable

remoteViews.setInt(R.id.layout, "setBackgroundResource", R.drawable.widget_background); 

我已经看到了这个问题:Call setImageDrawable from RemoteViews但我无法理解如何实现。我甚至找不到上面提到的setXYZ()。这是我迄今为止所尝试的:

  1. 使动态绘制渐变。在这种方法中,我无法设置背景,因为AFAIK所有的方法都以可绘制的id为标识,并且我有一个可绘制的对象。
  2. 尝试ImageView作为背景(在LinearLayout之前)。它没有为小部件提供适当的边距。由于小部件的文本是动态的,有时它超出这不是我想要的

  3. 制作bg.xml中,我有ImageView的的:

    <shape xmlns:android="http://schemas.android.com/apk/res/android" > 
         <padding 
          android:bottom="1dp" 
          android:left="1dp" 
          android:right="1dp" 
          android:top="1dp" /> 
         <corners 
          android:bottomLeftRadius="7dp" 
          android:bottomRightRadius="7dp" 
          android:topLeftRadius="7dp" 
          android:topRightRadius="7dp" /> 
    </shape> 
    

现在我完全糊涂了并卡住。有人可以帮助(可能更多的代码和更少的链接)尽快?此外,请不要因已经询问而关闭此问题。

+0

如何在您的LinearLayout下使用ImageView作为背景层? – harism

+0

我试了一下,但忘了提。它没有为小部件提供适当的边距。由于小部件文本是动态的,有时它会从imageView中走出,这不是我想要的 – harshit

回答

4

尝试ImageView作为背景(在LinearLayout之前)。它没有为小部件提供适当的边距。由于小部件的文本是动态的,有时它走出的ImageView的这不是我想要的

我不完全知道你的意思,但如果你使用的FrameLayout/RelativeLayout的为你的根布局,然后把ImageView里面填满父母,你的图像应该是你的小部件的大小。

<FrameLayout 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:layout_margin="6dp" > 

    <ImageView 
     android:id="@+id/widgetBg" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:scaleType="fitXY" /> 

    // Other views 

</FrameLayout> 

此外,这是我在做什么,以动态地改变圆角渐变背景的颜色&阿尔法。然后使用setImageViewBitmap()应用于imageview。可能有更好的方法。

public static Bitmap getBackground(int bgColor, int width, int height, Context context) { 
    try { 
     // convert to HSV to lighten and darken 
     int alpha = Color.alpha(bgColor); 
     float[] hsv = new float[3]; 
     Color.colorToHSV(bgColor, hsv); 
     hsv[2] -= .1; 
     int darker = Color.HSVToColor(alpha, hsv); 
     hsv[2] += .3; 
     int lighter = Color.HSVToColor(alpha, hsv); 

     // create gradient useng lighter and darker colors 
     GradientDrawable gd = new GradientDrawable(
       GradientDrawable.Orientation.LEFT_RIGHT,new int[] { darker, lighter}); 
     gd.setGradientType(GradientDrawable.RECTANGLE); 
     // set corner size 
     gd.setCornerRadii(new float[] {4,4,4,4,4,4,4,4}); 

     // get density to scale bitmap for device 
     float dp = context.getResources().getDisplayMetrics().density; 

     // create bitmap based on width and height of widget 
     Bitmap bitmap = Bitmap.createBitmap(Math.round(width * dp), Math.round(height * dp), 
       Bitmap.Config.ARGB_8888); 
     Canvas canvas = new Canvas(bitmap); 
     gd.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); 
     gd.draw(canvas); 
     return bitmap; 
    } catch (Exception e) { 
     e.printStackTrace(); 
     return null; 
    } 
}