如何通过代码将xml layer-list转换为layerdrawable

时间:2011-08-05 02:24:32

标签: android drawable

我正在尝试按代码编写以下xml。

----抽拉\ my_layerdrawable.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
      <bitmap android:src="@drawable/my_image"
        android:gravity="left"/>
    </item>
    <item android:left="10dp">
      <bitmap android:src="@drawable/my_image"
        android:gravity="left" />
    </item>
    <item android:top="10dp">
      <bitmap android:src="@drawable/my_image"
        android:gravity="left"/>
    </item>
    <item android:top="10dp" android:left="10dp">
      <bitmap android:src="@drawable/my_image"
        android:gravity="left" />
    </item>
    <item android:top="20dp">
      <bitmap android:src="@drawable/my_image"
        android:gravity="left"/>
    </item>
    <item android:top="20dp" android:left="10dp">
      <bitmap android:src="@drawable/my_image"
        android:gravity="left" />
    </item>
</layer-list>

我编码了下面的块,但它正在拉伸图像。

    InsetDrawable[] layers = new InsetDrawable[this.itemCount];

    Resources resources = getResources();

    ImageButton imgButton = (ImageButton) findViewById(R.id.btnItems);
    int layerTop = 0;
    for (int i = 0; i < this.itemCount; i++)
    {

        int layerLeft = i % 2 == 1 ? 5 : 0;

        Drawable dr = resources.getDrawable(R.drawable.my_image);
        layers[i] = new InsetDrawable(dr, layerLeft, layerTop, -layerLeft, -layerTop);

        layerTop += i % 2 == 1 ? 10 : 0;


    }

    LayerDrawable layerDrawable = new LayerDrawable(layers);

    imgButton.setImageDrawable(layerDrawable);

当我将可绘制的xml分配给imgButton时它正常工作没有拉伸或任何更改。

ImageButton imgButton = (ImageButton) findViewById(R.id.btnItems);
imgButton.setImageResource(R.drawable.my_layerdrawable);

您是否有任何想法通过代码使图层可绘制?

感谢。

1 个答案:

答案 0 :(得分:4)

您可以使用BitmapDrawable。

  

包装位图的Drawable,可以平铺,拉伸或对齐。您可以从文件路径,输入流,XML通胀或Bitmap对象创建BitmapDrawable。

您的代码将如下所示:

Drawable[] layers = new Drawable[this.itemCount];
Resources resources = getResources();
ImageButton imgButton = (ImageButton) findViewById(R.id.btnItems);

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);

for (int i = 0; i < this.itemCount; i++)
{
    Bitmap bm = BitmapFactory.decodeResource(resources, R.drawable.icon);
    BitmapDrawable bmd = new BitmapDrawable(bm);
    bmd.setGravity(Gravity.TOP);        
    bmd.setTargetDensity(metrics);
    layers[i] = bmd;   
}
LayerDrawable layerDrawable = new LayerDrawable(layers);

int layerTop = 0;
for (int i = 0; i < this.itemCount; i++)
{

    int layerLeft = i % 2 == 1 ? 5 : 0;
    layerDrawable.setLayerInset(i, layerLeft, layerTop, -layerLeft, -layerTop);
    layerTop += i % 2 == 1 ? 10 : 0;
}

imgButton.setImageDrawable(layerDrawable);