【问题标题】:how dynamically assign ring color如何动态分配环颜色
【发布时间】:2016-09-03 01:54:55
【问题描述】:

我们可以定义一个环形可绘制对象并在布局 xml 文件中使用它,如下所示,

是否可以定义一个可绘制的环并在运行时动态更改颜色?用例在列表项中,不同项中的环可能具有不同的环颜色。

搜索并没有找到好的解决方案,如果有人有一些建议,不胜感激。

<ImageView
                    android:layout_width="10dp"
                    android:layout_height="10dp"
                    android:src="@drawable/ring" />

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:top="4dp"
    android:right="4dp"
    android:bottom="4dp"
    android:left="4dp">
    <shape
        android:shape="oval">
        <solid android:color="#4d4d4d" />
    </shape>
</item>
<item>
    <shape
        android:shape="oval">
        <stroke android:width="2dp"
            android:color="#4d4d4d"/>
    </shape>
</item>

【问题讨论】:

  • 试试我的答案.. 工作正常...

标签: android android-drawable shape ring


【解决方案1】:

首先将 Id 放到你的图层中,像这样绘制

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/shape1"
        android:top="4dp"
        android:right="4dp"
        android:bottom="4dp"
        android:left="4dp">
        <shape
            android:shape="oval">
            <solid android:color="#4d4d4d" />
        </shape>
    </item>
    <item
        android:id="@+id/shape2"

        >
        <shape

            android:shape="oval">
            <stroke android:width="2dp"
                android:color="#4d4d4d"/>
        </shape>
    </item>
    </layer-list>

代码...

LayerDrawable shape = (LayerDrawable) ContextCompat.getDrawable(demo.this,R.drawable.ring);
GradientDrawable gradientDrawable1 = (GradientDrawable) shape.findDrawableByLayerId(R.id.shape1);

GradientDrawable gradientDrawable2 = (GradientDrawable) shape.findDrawableByLayerId(R.id.shape2);

gradientDrawable1.setColor(ContextCompat.getColor(demo.this,R.color.color_first));

gradientDrawable2.setColor(ContextCompat.getColor(demo.this,R.color.color_second));// changing to black color

ImageView imageView=(ImageView)findViewById(R.id.imageview);
imageView.setBackground(shape);

【讨论】:

  • 谢谢阿琼!如果环形可绘制对象有两种颜色的一个形状:schemas.android.com/apk/res/android" android:shape="ring" android:useLevel ="false">
  • 今天我不在电脑上,但你可以尝试在 中设置颜色形状并将 id 设置为项目,然后设置颜色.....
  • 还有一些方法,如果环有两种颜色,一种是两种,整体会随着答案而改变,如果想用这种方法改变颜色 shape.setStroke(strokeWidth,color) 设置宽度 int 和颜色喜欢上面的答案....
猜你喜欢
  • 1970-01-01
  • 2018-05-18
  • 1970-01-01
  • 2022-01-24
  • 1970-01-01
  • 2017-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多