2014-09-01 93 views
3

我有一個形象上我把一個彩色疊加,像這樣(的顏色從here拍攝):設置漸變背景通過編程

佈局/ list_item_view.xml

<View 
    android:id="@+id/image_cover_gradient" 
    android:layout_width="fill_parent" 
    android:layout_height="80dip" 
    android:layout_alignParentTop="true" 
    android:layout_marginTop="70dp" 
    android:background="@drawable/gradient_blue"   
    /> 

繪製/ gradient_blue.xml

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
<item> 
    <shape> 
     <gradient 
      android:angle="90" 
      android:startColor="@color/CornflowerBlue" 
      android:endColor="@color/Transparent" 
      android:type="linear" /> 
    </shape> 
</item> 
</selector> 

這總是會產生一個藍色覆蓋層(CornflowerBlue),並且它按預期工作。

現在我試圖以編程方式執行此操作,並遵循一些stackoverflow答案(如this),但仍然無法使其工作。這裏是我的代碼:

private void setColor(int color){ 
    View gradientCover = view.findViewById(R.id.image_cover_gradient); 
    // this FAILS because it's a StateListDrawable 
    //GradientDrawable coverGd = (GradientDrawable) gradientCover.getBackground(); 
    //coverGd.setColor(color); 

    //this doesn't seem to work either (I don't see any effect on the image) 
    GradientDrawable drawable = new GradientDrawable(
      Orientation.BOTTOM_TOP, new int[] { color, resources.getColor(R.color.Transparent) 
      }); 
    StateListDrawable sld = new StateListDrawable(); 
    sld.addState(new int[] { android.R.attr.startColor, android.R.attr.endColor}, drawable); 
    gradientCover.setBackground(sld); 
} 

感謝您的幫助。

+1

擺脫StateListDrawable的,你需要的是GradientDrawable – pskink 2014-09-01 14:21:56

回答

3

由於@pskink建議 - 去除StateListDrawable解決它:

GradientDrawable drawable = new GradientDrawable(
    Orientation.BOTTOM_TOP, new int[] { color, resources.getColor(R.color.Transparent) 
});  
gradientCover.setBackground(drawable); 
+0

,你爲什麼張貼嗎? – k0sh 2014-09-02 08:59:00