如何以编程方式制作可绘制形状(Android) [英] How to make a drawable Shape programmatically (Android)

查看:74
本文介绍了如何以编程方式制作可绘制形状(Android)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作自定义TextView(Java类),并且在翻译"行时遇到麻烦(在原始TextView" xml上)

i'm making a custom TextView (Java class) and i'm having trouble "to translate" the line (on "original TextView" xml)

android:background="@drawable/myDrawableShape"

更改为Java void以更改"myDrawableShape"的颜色

to a java void to change the color of the "myDrawableShape"

myDrawableShape.xml

myDrawableShape.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="#ffafafaf" />
<corners android:radius="15dp" />

我将从字符串中设置颜色,例如,以编程方式更改颜色的空缺可能是

I'll get the color to set from a String, the void to change the color programmatically could be (for example)

void colorSet(String color)

提前谢谢!

推荐答案

然后,您可以使用以下代码在Java本身中创建Shape Drawable.

You can then create your Shape Drawable in Java itself using below code.

public Drawable getRoundRect() {
    RoundRectShape rectShape = new RoundRectShape(new float[]{
            10, 10, 10, 10,
            10, 10, 10, 10
    }, null, null);

    ShapeDrawable shapeDrawable = new ShapeDrawable(rectShape);
    shapeDrawable.getPaint().setColor(Color.parseColor("#FF0000"));
    shapeDrawable.getPaint().setStyle(Paint.Style.FILL);
    shapeDrawable.getPaint().setAntiAlias(true);
    shapeDrawable.getPaint().setFlags(Paint.ANTI_ALIAS_FLAG);
    return shapeDrawable;
}

这篇关于如何以编程方式制作可绘制形状(Android)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆