2011-02-09 103 views
15

我正在试验可绘制背景,迄今为止没有任何问题。在运行时在Android上更改渐变背景颜色

我现在试图在运行时更改渐变背景颜色。

不幸的是,没有API可以在运行时改变它,看来。即使尝试mutate()drawable,如下所述:Drawable mutations

示例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?

回答

32

是的!找到了一个方法!

有大约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背景。现在我可以编程设置背景颜色。

+2

是否有可能提供一个角度值? – Ahmed 2013-02-19 18:09:32

0

根据您的要求,使用color state list而不是固定颜色的startColor和endColor可能会做你想做的。

+0

有趣的选择,但我真的需要更有活力的东西。这是一个列表,显示来自不同可插拔提供者的信息。每个供应商都有自定义颜色,因此用户知道该信息来自哪里。我知道这不是很多信息,但也许会有所帮助。 – Phenome 2011-02-09 09:21:28

9

我尝试使用Phenome的按钮视图解决方案。但不知何故,它没有奏效。

我想出了别的东西:(礼貌:Android的API演示示例)

package com.example.testApp; 

import android.app.Activity; 
import android.graphics.drawable.GradientDrawable; 
import android.os.Bundle; 
import android.view.View; 

public class TetApp extends Activity { 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     View v = findViewById(R.id.btn); 
     v.setBackgroundDrawable(new DrawableGradient(new int[] { 0xff666666, 0xff111111, 0xffffffff }, 0).SetTransparency(10)); 

    } 

    public class DrawableGradient extends GradientDrawable { 
     DrawableGradient(int[] colors, int cornerRadius) { 
      super(GradientDrawable.Orientation.TOP_BOTTOM, colors); 

      try { 
       this.setShape(GradientDrawable.RECTANGLE); 
       this.setGradientType(GradientDrawable.LINEAR_GRADIENT); 
       this.setCornerRadius(cornerRadius); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 

     public DrawableGradient SetTransparency(int transparencyPercent) { 
      this.setAlpha(255 - ((255 * transparencyPercent)/100)); 

      return this; 
     } 
    } 
} 
0

尝试下面我的代码:

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)); 
}