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

时间:2013-12-18 08:58:02

标签: android background drawable resource-id

我想将图片作为布局的背景。

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

API级别8 layout.setBackground( d ) 不支持layout.setBackgroundDrawable( d ) 已弃用所以我需要使用< / p>

layout.setBackgroundResource(resourceID)

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

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

创建一个drawable。

4 个答案:

答案 0 :(得分: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);
    }

答案 1 :(得分:0)

答案 2 :(得分:0)

对于API 1-15使用

view.setBackgroundDrawable(drawable);

对于API 16&amp;以上使用

viw.setBackground(drawable);

答案 3 :(得分:0)

正如POST @hasanghaforian所述,

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

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

OR

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

其中,

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

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

相关问题