2013-08-05 10 views
2

내 애플리케이션에서 각 listView 항목의 배경색을 변경하려고합니다. 그리고 그 때문에 레이어 목록에있는 모양을 사용하고 있습니다. 여기java.lang.ClassCastException : android.graphics.drawable.LayerDrawable을 android.graphics.drawable.GradientDrawable에 캐스팅 할 수 없습니다.

drop_shadow.xml 내 코드입니다

<layer-list xmlns:android="http://schemas.android.com/apk/res/android"> 

    <item> 
     <shape android:shape="rectangle"> 

      <gradient android:startColor="#B7B7B7" 
         android:endColor="#A1A1A1" 
         android:angle="270"/> 
      <corners android:radius="10dp" /> 

     </shape> 
    </item> 

    <item android:top="1px"> 

     <shape android:shape="rectangle"> 

      <solid android:color="@color/color11"/> 
      <corners android:radius="10dp" /> 
     </shape> 

    </item> 

</layer-list> 

main.xml에 나는이 메서드를 호출 할 때

<RelativeLayout 
       android:orientation="vertical" 
       android:id="@+id/mainLayout" 
       android:layout_width="match_parent" 
       android:layout_height="match_parent" 
       android:background="@drawable/drop_shadow"/> 

나는

private void setRoundedBackground(View view,int color){ 
     GradientDrawable gradientDrawable; 
     gradientDrawable = (GradientDrawable) view.getBackground().mutate(); 
     gradientDrawable.setColor(getResources().getColor(color)); 
     gradientDrawable.invalidateSelf(); 

    } 

가 어떻게 ClassCastException이 얻을 수있다 LayerDrawable의 GradientDrawable ?

답변

4

SomeDrawable drawable = new SomeDrawable(Color.parseColor("Start Color Code"),Color.parseColor("Center Color Code"),Color.parseColor("End Color Code"),1,Color.BLACK,00); 
yourLayout.setBackgroundDrawable(drawable); 
0

그들은 둘 다 Drawable의 하위 클래스이므로 서로를 부모 클래스에만 캐스트 할 수 없습니다. 당신이 .. 동적으로 그라데이션 당김을 만들 클래스

import android.graphics.drawable.GradientDrawable; 

    public class SomeDrawable extends GradientDrawable { 

    public SomeDrawable(int pStartColor, int pCenterColor, int pEndColor, int pStrokeWidth, int pStrokeColor, float cornerRadius) { 
     super(Orientation.BOTTOM_TOP,new int[]{pStartColor,pCenterColor,pEndColor}); 
     setStroke(pStrokeWidth,pStrokeColor); 
     setShape(GradientDrawable.RECTANGLE); 
     setCornerRadius(cornerRadius); 
    } 
} 

이하로 사용하고 아래로이 클래스를 사용할 수 있습니다

+0

그것은 당신이 원하는에 따라 달라집니다 – fish40

+0

최고의 솔루션으로 여기 변경해야합니까 GradientDrawable 함께 할 – pshegger

+0

단색을 프로그래밍 방식으로 변경하고 싶습니다 (이 예제에서는 color11) – fish40

관련 문제