6

我想将图像作为Layout的背景。

首先,我正在创建一个可绘制对象:Drawable d = Drawable.createFromPath("pathToImageFile");

API 级别 8 layout.setBackground( d )不受支持并且 layout.setBackgroundDrawable( d ) 已弃用 ,因此我需要使用

layout.setBackgroundResource(resourceID)

如何获取动态生成的drawable的resourceID。我正在使用这种方法:

Drawable d = Drawable.createFromPath("pathToImageFile");

创建一个drawable。

4

4 回答 4

2

你好用下面的方法

public void setBackgroundDrawable (Drawable background) 

通过调用

imageView.setBackgroundDrawable(drawable);

在 API 级别 1 中添加

编辑:试试这个方法

@SuppressWarnings("deprecation")
    private void setRes(ImageView iv,Drawable drawable){
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
            iv.setBackground(drawable);
        else
            iv.setBackgroundDrawable(drawable);
    }
于 2013-12-18T09:19:08.910 回答
0

正如@hasanghaforian 在帖子中解释的那样,

您可以通过以下代码使用“ getIdentifier ”获取资源 ID :

int resID = getResources().getIdentifier("org.anddev.android.testproject:drawable/bug", null, null);

或者

int resID = getResources().getIdentifier("bug", "drawable", "org.anddev.android.testproject");      

在哪里,

bug.png是“ /res/drawable/”中的文件。

然后你可以使用layout.setBackgroundResource(resID).

于 2013-12-18T09:57:59.910 回答
0

使用setBackground(Drawable background)方法。http://developer.android.com/reference/android/view/View.html#setBackground(android.graphics.drawable.Drawable)

于 2013-12-18T09:01:36.927 回答
0

对于 API 1-15 使用

view.setBackgroundDrawable(drawable);

对于 API 16 及以上使用

viw.setBackground(drawable);
于 2013-12-18T09:49:35.470 回答