【问题标题】:How to change the color of a shape that is inside a selector programatically?如何以编程方式更改选择器内的形状的颜色?
【发布时间】:2017-02-21 16:11:58
【问题描述】:

这是针对 api

<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:state_pressed="true">

    <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">

        <size
            android:width="60dp"
            android:height="60dp" />

        <solid android:color="#007fa9" />

    </shape>
</item>

<item android:id="@+id/shape_id" >
    <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">

        <size
            android:width="60dp"
            android:height="60dp"
            />

        <solid android:color="#007fa9" />
    </shape>
</item>

</selector>

如您所见,我有一个包含内部状态和形状的选择器,如何以编程方式更改形状的纯色?我将它设置为相对布局的背景,所以它的行为就像一个按钮在按下时改变它的颜色,或者也许有一种方法可以以编程方式创建一个形状,如果是这样的话如何?

对于 api 21 及以上版本

<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="#007fa9">

<item android:id="@android:id/mask">

    <shape android:shape="oval">

        <solid android:color="#007fa9" />

    </shape>

</item>

<item>
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="oval">

        <size
            android:width="60dp"
            android:height="60dp" />

        <solid android:color="#007fa9" />

    </shape>

</item>

</ripple>

你是怎么做到这一点的?

【问题讨论】:

标签: java android android-layout xml-drawable rippledrawable


【解决方案1】:

试试这个:

给你的 Drawable 选择器一个 id:

<item  android:id="@+id/shape_id">

然后在代码中:

LayerDrawable shape = (LayerDrawable) ContextCompat.getDrawable(YourActivity.this,R.drawable.shape_id); //get the ID
shape.setColor(Color.Black); // change color

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-09
    • 2015-11-16
    • 1970-01-01
    • 1970-01-01
    • 2016-10-11
    • 2019-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多