LayerDrawable以编程方式 [英] LayerDrawable programmatically

查看:162
本文介绍了LayerDrawable以编程方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于我的应用程序的颜色主题是动态的,所以我只能使用颜色和shapedrawables创建背景可绘制对象, 我想构建一个可绘制颜色和形状可绘制的edittext背景,如下所示. 但是我想以编程方式做到这一点

Since my application's color theme is dynamic i can only create background drawables using colors and shapedrawables, i want to build a edittext background drawable with colors and shapes as shown below. But i want to do this programatically

如何通过编程方式构建相同的可绘制对象?

How to build this same drawable programatically?

<item>
    <shape>
        <solid android:color="@android:color/yellow" />
    </shape>
</item>

<!-- main color -->
<item
    android:bottom="1dp"
    android:left="1dp"
    android:right="1dp">
    <shape>
        <solid android:color="@android:color/white" />
    </shape>
</item>

<!-- draw another block to cut-off the left and right bars -->
<item android:bottom="10dp">
    <shape>
        <solid android:color="@android:color/white" />
    </shape>
</item>

这就是我尝试过的......

this is what i tried....

    GradientDrawable border = new GradientDrawable();
    border.setShape(GradientDrawable.RECTANGLE);
    border.setColor(Color.WHITE);

    GradientDrawable background = new GradientDrawable();
    background.setShape(GradientDrawable.RECTANGLE);
    background.setColor(Color.YELLOW);


    GradientDrawable clip = new GradientDrawable();
    clip.setShape(GradientDrawable.RECTANGLE);
    border.setColor(Color.WHITE);

    Drawable[] layers = {background, border, clip};
    LayerDrawable layerDrawable = new LayerDrawable(layers);

    layerDrawable.setLayerInset(0, 0, 0, 0, 0);
    layerDrawable.setLayerInset(1, 1, 0, 1, 1);
    layerDrawable.setLayerInset(2, 0, 0, 0, 10);

但是结果不一样....请帮助....!

but the result is different....please help....!

推荐答案

我终于使它起作用了.我没有使用GradientDrawable,而是使用了ShapeDrawable.

I finally got it working. Instead of using GradientDrawable I used ShapeDrawable.

通过将此LayerDrawable设置为EditText背景,您可以重新生成默认的EditText 自定义颜色的样式.

By setting this LayerDrawable as an EditText background you can regenerate default EditText styles with custom colors.

ShapeDrawable border = new ShapeDrawable();
border.getPaint().setColor(Color.WHITE);

ShapeDrawable background = new ShapeDrawable();
background.getPaint().setColor(Color.BLACK);


ShapeDrawable clip = new ShapeDrawable();
clip.getPaint().setColor(Color.WHITE);

Drawable[] layers = {background, border, clip};
LayerDrawable layerDrawable = new LayerDrawable(layers);

layerDrawable.setLayerInset(0, 0, 0, 0, 0);
layerDrawable.setLayerInset(1, 1, 0, 1, 1);
layerDrawable.setLayerInset(2, 0, 0, 0, 10);

这篇关于LayerDrawable以编程方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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