【问题标题】:Changing color in a shape inside a layer-list programmatically以编程方式更改图层列表内形状的颜色
【发布时间】:2014-01-09 10:56:07
【问题描述】:

我正在尝试以编程方式更改 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>

我在 Fragment 中调用以下代码

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.为什么我在 shape.setColor 中得到 NullPointerException?

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

【问题讨论】:

    标签: android shape android-drawable layerdrawable


    【解决方案1】:

    好的,我找到了答案,我只需要将形状的 id 放在项目中而不是形状中 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)

    【讨论】:

    • 但是我遇到了同样的问题。这对我不起作用
    • 好吧@jincyabraham你可以得到视图然后它的背景drawable然后得到形状作为gradiendrawable在这里link
    • 能否请您说明您为获取形状对象做了哪些步骤,不清楚。
    • 这适用于 GradientDrawable,但不适用于我尝试在运行时定义的颜色的 RotateDrawable。有什么想法吗?
    猜你喜欢
    • 2015-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多