Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/190.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
运行时在Android上更改渐变背景色_Android_Background_Gradient_Drawable - Fatal编程技术网

运行时在Android上更改渐变背景色

运行时在Android上更改渐变背景色,android,background,gradient,drawable,Android,Background,Gradient,Drawable,我正在试验可绘制的背景,到目前为止没有任何问题 我现在尝试在运行时更改渐变背景色 不幸的是,似乎没有API在运行时对其进行更改。即使尝试对drawable()进行变异也不行,如下所述: 示例XML如下所示。正如预期的那样,它起作用了 <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <gradient andro

我正在试验可绘制的背景,到目前为止没有任何问题

我现在尝试在运行时更改渐变背景色

不幸的是,似乎没有API在运行时对其进行更改。即使尝试对drawable()进行变异也不行,如下所述:

示例XML如下所示。正如预期的那样,它起作用了

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient
        android:startColor="#330000FF"
        android:endColor="#110000FF"
        android:angle="90"/>
</shape>

遗憾的是,我想要一个有各种颜色的列表,它们必须在运行时通过编程进行更改


是否有其他方法在运行时创建此渐变背景?甚至可能不完全使用XML?

根据您的需求,使用startColor和endColor代替固定颜色可能会满足您的需要。

是的!找到了一条路

我不得不忘记XML,但我是这样做的:

在我的getView()重载函数(ListAdapter)上,我必须:

    int h = v.getHeight();
    ShapeDrawable mDrawable = new ShapeDrawable(new RectShape());
    mDrawable.getPaint().setShader(new LinearGradient(0, 0, 0, h, Color.parseColor("#330000FF"), Color.parseColor("#110000FF"), Shader.TileMode.REPEAT));
    v.setBackgroundDrawable(mDrawable);

这给了我与上面XML背景相同的结果。现在我可以通过编程设置背景色。

我尝试使用Phenome的按钮视图解决方案。但不知怎的,它没有起作用

我还想到了一些别的东西:(礼貌:Android API演示示例)

请尝试下面的代码:

 int[] colors = new int[2];
            colors[0] = getRandomColor();
            colors[1] = getRandomColor();


            GradientDrawable gd = new GradientDrawable(
                    GradientDrawable.Orientation.TOP_BOTTOM, colors);

            gd.setGradientType(GradientDrawable.RADIAL_GRADIENT);
            gd.setGradientRadius(300f);
            gd.setCornerRadius(0f);
            YourView.setBackground(gd);
生成随机颜色的方法:

public static int getRandomColor(){
    Random rnd = new Random();
    return Color.argb(255, rnd.nextInt(256), rnd.nextInt(56), rnd.nextInt(256));
}

有趣的选择,但我真的需要更具活力的东西。它是一个列表,显示来自不同可插拔提供商的信息。每个提供者都有一个自定义颜色,因此用户知道信息来自何处。我知道这并不是很多信息,但可能会有所帮助。是否可以在上面给出一个角度值?如果您在活动中使用此值,您可能希望在onWindowFocusChanges()中而不是onCreate()中运行此值。
public static int getRandomColor(){
    Random rnd = new Random();
    return Color.argb(255, rnd.nextInt(256), rnd.nextInt(56), rnd.nextInt(256));
}