【问题标题】:Change bottom property of item of layer-list Drawable programmatically以编程方式更改图层列表可绘制项的底部属性
【发布时间】:2015-10-12 01:36:43
【问题描述】:

我正在创建一个 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);

有人知道吗?

【问题讨论】:

    标签: android layer-list layerdrawable


    【解决方案1】:

    这是一个老问题,但我想我仍然在这里发布答案,以防它对某人有所帮助。

    以编程方式更改层列表底部属性的方法是使用layerDrawable.setLayerInset(index, left, top, right, bottom); 在这个问题示例中:

    LayerDrawable layerDrawable = (LayerDrawable) v.getContext().getResources().getDrawable(R.drawable.layer_list_navigation_with_border);
    layerDrawable.setLayerInset(1, 0, 0, 0, bottom);
    

    其中bottom 是所需dp 的像素值。

    希望这对某人有所帮助。

    【讨论】:

      【解决方案2】:

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

      我创建了一个可绘制的图层列表并动态更改其项目颜色。 代码如下:

      <?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);
      

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-04-13
        • 1970-01-01
        • 2013-03-09
        • 1970-01-01
        • 1970-01-01
        • 2021-09-03
        • 2012-07-07
        相关资源
        最近更新 更多