如何动态改变椭圆形的颜色

时间:2022-11-21 12:34:53

Need to place icon in center of the oval with solid color. It also needs to allow dynamically change the oval's color.

需要在纯色的椭圆形中心放置图标。它还需要允许动态改变椭圆的颜色。

Could show the icon on top/center of the oval like this by Jérémie Laval:

可以通过JérémieLaval在椭圆形的顶部/中心显示图标:

<?xml version="1.0" encoding="UTF-8" ?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
    <solid android:color="#42000000" />
    <padding android:left="8dp" android:top="8dp"
         android:right="8dp" android:bottom="8dp" />
</shape>

<FrameLayout
   android:layout_width="80dp"
   android:layout_height="80dp"
   android:layout_gravity="center"
   android:background="@drawable/aitemring">
   <ImageView
   android:src="@drawable/coffee"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:scaleType="center" />
</FrameLayout>

The question how to change the color of the oval shape in code (kets say got new color #ff0000, or any non-predefined color)?

如何在代码中改变椭圆形状的颜色的问题(kets说得到新的颜色#ff0000,或任何非预定义的颜色)?

2 个解决方案

#1


Have you thought about just defining two drawables and swapping them when you need to change the color?

您是否考虑过只需定义两个drawable并在需要更改颜色时交换它们?

You can do a layer-list to create your shape and add the icon.

您可以执行图层列表来创建形状并添加图标。

#2


With David's hint, this works:

有了大卫的暗示,这有效:

<?xml version="1.0" encoding="UTF-8" ?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
    <solid android:color="#42000000" />
    </shape>


<ImageView
    android:id="+id/theIcon"
    android:src="@drawable/coffee"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:scaleType="center"
    android:background="@drawable/aitemring" />

GradientDrawable shapeDrawable = (GradientDrawable)theIcon.getBackground();
    shapeDrawable.setColor(0xffff0000);

#1


Have you thought about just defining two drawables and swapping them when you need to change the color?

您是否考虑过只需定义两个drawable并在需要更改颜色时交换它们?

You can do a layer-list to create your shape and add the icon.

您可以执行图层列表来创建形状并添加图标。

#2


With David's hint, this works:

有了大卫的暗示,这有效:

<?xml version="1.0" encoding="UTF-8" ?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
    <solid android:color="#42000000" />
    </shape>


<ImageView
    android:id="+id/theIcon"
    android:src="@drawable/coffee"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:scaleType="center"
    android:background="@drawable/aitemring" />

GradientDrawable shapeDrawable = (GradientDrawable)theIcon.getBackground();
    shapeDrawable.setColor(0xffff0000);