Android:使用图像路径设置布局背景

ZZe*_*aNN 6 android background drawable resource-id

我想把图像作为布局的背景.

首先,我正在创建一个drawable: Drawable d = Drawable.createFromPath("pathToImageFile");

API级别8 layout.setBackground( d )不支持layout.setBackgroundDrawable( d ) 不推荐使用 ,所以我需要使用

layout.setBackgroundResource(resourceID)

如何获取动态生成的drawable的resourceID.我正在使用此方法:

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

创造一个可绘制的.

din*_*rma 2

您好使用以下方法

public void setBackgroundDrawable (Drawable background) 
Run Code Online (Sandbox Code Playgroud)

通过致电

imageView.setBackgroundDrawable(drawable);
Run Code Online (Sandbox Code Playgroud)

添加到 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);
    }
Run Code Online (Sandbox Code Playgroud)