android - 以编程方式更改图层列表 Drawable 项的底部属性

标签 android layer-list layerdrawable

我正在创建一个 LayerDrawable 来创建底部笔划,但我不知道如何给出图层的底部边距 (Drawablw)。

    <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:bottom="2dp">
      ..
        </item>
    </layer-list>

我想像上面那样以编程方式设置底部边距。

到目前为止我已经这样做了:

Drawable[] list = new Drawable[2];
GradientDrawable strokeDrawable = new GradientDrawable(
    GradientDrawable.Orientation.TOP_BOTTOM, new int[] {
        strokeColor[0], strokeColor[0] });
GradientDrawable backgroundDrawable = new GradientDrawable(
    GradientDrawable.Orientation.TOP_BOTTOM, bgColor);
// Now how to set bottom margin to make border. 

list[0] = strokeDrawable;
list[1] = backgroundDrawable;

LayerDrawable layerDrawable = new LayerDrawable(list);

有人知道吗?

最佳答案

经过大量挖掘,我找到了解决方案,虽然它解决了我的问题,但它不是我想要的。

我创建了一个图层列表可绘制对象并动态更改了它的项目颜色。 这是代码:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

<item android:id="@+id/item_bottom_stroke" >
    <shape android:shape="rectangle">
        <solid android:color="#0096FF"/>
    </shape>
</item>
<item android:id="@+id/item_navbar_background" android:bottom="1dp" >
    <shape android:shape="rectangle">
        <solid android:color="#FFFFFF"/>
    </shape>
</item>

以下代码在运行时修改上面的可绘制对象以更改其颜色。

LayerDrawable layerDrawable = (LayerDrawable) v.getContext().getResources().getDrawable(R.drawable.layer_list_navigation_with_border);
GradientDrawable strokeDrawable = (GradientDrawable) layerDrawable.findDrawableByLayerId(R.id.item_bottom_stroke);
strokeDrawable.setColor(strokeColor[0]);
GradientDrawable backgroundColor = (GradientDrawable) layerDrawable.findDrawableByLayerId(R.id.item_navbar_background);
backgroundColor.setColors(bgColor);

已发布的解决方案,认为有人可能会受益。

关于android - 以编程方式更改图层列表 Drawable 项的底部属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31558705/

相关文章:

android - 在ViewPager Webview内实现单击功能

java - 如何使用pid杀死进程

android - 将 ColorFilter 应用于 LayerDrawable 中的 Drawable

android - Drawable 已经属于另一个所有者,但不公开常量状态

android - 创建用于测试的模拟 Activity 的最快方法

android - 使用gradle的android格式源代码

Android - 图层列表椭圆形有额外的内线

android shape xml旋转drawable以编程方式更改颜色

Android RecyclerView 不以编程方式更改第一项的背景颜色

imagebutton - 自定义LayerDrawable : onStateChange never called