android - 以编程方式将以下代码 xml 创建到 layerlist android

标签 android android-drawable layer-list android-shape android-shapedrawable

我必须将此背景设置为具有不同颜色的许多 View 。但如果我这样做,xml 将是大约 20 个文件,这是巨大的,所以我想将以下 xml layer-list 转换为程序化的方式进入完全独立的模块,甚至没有一个 xml,以便它可以重复使用,请帮助我。

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    //i can create this drawable
    <item>
        <shape android:shape="rectangle">
            <solid android:color="#ff2632"/>
        </shape> </item>

    //I don't know how to achieve this one, especially this "bottom property"
    <item android:bottom="2dp">
        <shape android:shape="rectangle">
            <solid android:color="#d7ffa2"/>
        </shape> </item>
</layer-list>

最佳答案

请找到下面的代码,

// This is the first item in your XML file
GradientDrawable layer1 = new GradientDrawable();
layer1.setShape(GradientDrawable.RECTANGLE);
layer1.setColor(Color.parseColor("#ff2632"));

// This is your second item in your XML file
GradientDrawable layer2 = new GradientDrawable();
layer2.setShape(GradientDrawable.RECTANGLE);
layer2.setColor(Color.parseColor("#d7ffa2"));

// This will give the bottom space which you are unable to do    
InsetDrawable insetLayer2 = new InsetDrawable(layer2, 0, 0, 0, 2);

// This is the final drawable which is to be used
LayerDrawable layerDrawable = new LayerDrawable(new Drawable[]{layer1, insetLayer2});

引用这个,让我知道问题。

关于android - 以编程方式将以下代码 xml 创建到 layerlist android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34352691/

相关文章:

Android,没有模拟器的基本代码测试

android - 使用设置了三种以上颜色的 gradientDrawable

java - android studio 中带有 setImageDrawable 方法的 NullPointerException

Android::Layer-List 3 垂直矩形堆栈问题

android - 带按钮的自定义 View

android - 三星手机在 logcat 上发出大量日志消息

java - 显示一个包含选择文件和相机内容的对话框

android - Retrofit (1-2) 中的动态 header 不起作用

android - 如何在EditText中添加两个drawableRight?

android - Lollipop 前层列表中的项目大小不正确