如何在Android中编程创建可绘制的形状

3
我正在制作一个自定义的TextView(Java类),但是我在“原始TextView”xml上找不到正确的翻译方法来解决这一行问题。
android:background="@drawable/myDrawableShape"

将Java void应用于更改“myDrawableShape”颜色

myDrawableShape.xml

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

我将从一个字符串中获取颜色设置,通过以下void程序更改颜色:

void colorSet(String color)

提前致谢!


我不太明白你的问题。你是在问如何通过编程方式将TextView的背景设置为可绘制对象吗?如果是这样,以下是代码(ContextCompat是v4支持库的一部分):textView.setBackground(ContextCompat.getDrawable(MyActivity.this, R.drawable.myDrawableShape)); - tim.paetz
这篇帖子中有解释。请看第一个答案。 - Pavel Bochkarev
抱歉我的英语不好!!不,我想从代码中更改XML drawable上的“android:color =”#ffafafaf“。所以现在它的工作方式是,每种颜色都需要一个XML。我想要的是在从customTextview类创建textview时从代码中更改颜色,例如createText(String color)。 - ieselisra
2个回答

11

您可以使用以下代码在Java中创建自己的形状Drawable。

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;
}

工作了! - ieselisra

1
修改颜色:
  TextView tv= (TextView) findViewById(R.id.txt_time);

    Drawable background = getResources().getDrawable(R.drawable.test);

    if (background instanceof ShapeDrawable) {
        // If 'ShapeDrawable'
        ShapeDrawable shapeDrawable = (ShapeDrawable) background;
        shapeDrawable.getPaint().setColor(ContextCompat.getColor(this,R.color.colorAccent));
    } else if (background instanceof GradientDrawable) {
        // If'GradientDrawable'
        GradientDrawable gradientDrawable = (GradientDrawable) background;
        gradientDrawable.setColor(ContextCompat.getColor(this,R.color.colorPrimary));
    } else if (background instanceof ColorDrawable) {
        // If ColorDrawable
        ColorDrawable colorDrawable = (ColorDrawable) background;
        colorDrawable.setColor(ContextCompat.getColor(this,R.color.colorPrimaryDark));
    }
    tv.setBackground(background);

返回错误信息:“因为在Drawable上加载了GradientDrawable”:/ - ieselisra
Muthukrishnan Rajendran的代码完美运行,但还是谢谢! - ieselisra

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接