2013-12-20 180 views
18

我试图以编程方式更改selectable_kachel_shape的颜色。下面是XML文件:以编程方式更改层列表中形状的颜色

kachel_ticked_style.xml

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


    <item> 
     <shape 
      android:id="@+id/selectable_kachel_shape" 
      android:shape="rectangle" > 
      <stroke 
       android:width="5dp" 
       android:color="@color/headrbar_color" /> 
     </shape> 
    </item> 
    <item> 
     <rotate 
      android:fromDegrees="45" 
      android:pivotX="120%" 
      android:pivotY="100%" 
      android:toDegrees="45" > 
      <shape android:shape="line" > 
       <stroke 
        android:width="40dp" 
        android:color="@color/headrbar_color" /> 
      </shape> 
     </rotate> 
    </item> 
    <item 
     android:right="5dp" 
     android:top="5dp"> 
     <bitmap 
      android:gravity="top|right" 
      android:src="@drawable/selectable_tiles_check" /> 
    </item> 

</layer-list> 

我一个片段中调用以下代码

LayerDrawable layers = (LayerDrawable) this.getActivity().getResources().getDrawable(R.drawable.kachel_ticked_style); 

GradientDrawable shape = (GradientDrawable) (layers.findDrawableByLayerId(R.id.selectable_kachel_shape)); 
         shape.setColor(this.getActivity().getResources().getColor(android.R.color.background_dark); 

1.为什么我在形状歌厅一个NullPointerException。 setColor

2.如何以编程方式更改形状内部的颜色,即图层列表中的颜色?

回答

24

好,我找到了答案,我只是把形状的标识的项,里面没有形状 kachel_ticked_style.xml

<item 
    android:id="@+id/selectable_kachel_shape"> 
     <shape 
      android:shape="rectangle" > 
      <stroke 
       android:width="5dp" 
       android:color="@color/headrbar_color" /> 
     </shape> 
    </item> 

然后你就可以更改的任何颜色形状调用shape.setColor或中风调用shape.setStroke(strokeWidth,则strokeColor)

+0

的颜色,但我有相同problem.This不工作对我来说 –

+0

嘛@ji ncyabraham你可以得到视图然后它的背景可绘制然后得到形状作为gradiendrawable在这里[链接](http://stackoverflow.com/questions/16636412/change-shape-solid-color-at-runtime-inside- drawable-xml-used-as-background) – M090009

+0

你可以请你说明你做了什么步骤来获取形状对象,目前还不清楚。 –

相关问题