我想将图片作为布局的背景。
首先我要创建一个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。
答案 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)
使用setBackground(Drawable background)
方法。 http://developer.android.com/reference/android/view/View.html#setBackground(android.graphics.drawable.Drawable)
答案 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)
。