2011-02-09 101 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)); 
}