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

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

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

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

layout.setBackgroundResource(resourceID)

如何获得动态生成的可绘制对象的resourceID。我正在使用以下方法:

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

来创建一个可绘制对象。

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

这个方法已经被弃用了,我还能使用它吗?在Eclipse中,代码上显示了一个删除线。 - ZZeyaNN
这个方法在API 16及以上版本已被弃用,但在API 15及以下版本仍能正常工作。 - dinesh sharma
非常感谢。我也在考虑这种方法。但是在Eclipse中的删除标记仍然存在。即使使用了@SuppressWarnings("deprecation")@SuppressLint("NewApi") - ZZeyaNN
1
它会显示删除线,因为您可能已将Android SDK更新到15级以上,所以不用担心。 - dinesh sharma

0

使用API 1-15

view.setBackgroundDrawable(drawable);

对于 API 16 及以上版本,请使用

viw.setBackground(drawable);

0

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

您可以使用以下代码使用“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)来设置背景。


由于我们正在动态创建drawable,因此我们不知道它的名称,在这种情况下它的名称是“bug”。 - ZZeyaNN

0

问题仍然存在。它还使用API级别16。 - ZZeyaNN
1
从API级别1开始使用setBackgroundDrawable(Drawable background)。 - Shashika
已被弃用,现在不能使用。 - ZZeyaNN
它在API级别16中已被弃用。因此,您可以使用这个。如果您使用API 16或更高版本,请使用setBackground方法。 - Shashika

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接