1

我有一个视图,它有一个方法setBackgroundImage(BitmapDrawable),并且我imgbg在 res 的 drawable 文件夹中有一个图像。

如何将此图像设置为背景图像?

view.setBackgroundImage(R.drawable.imgbg);不能像R.drawable.imgbg整数一样工作,但方法需要可绘制。

我知道这很愚蠢,但即使经过密集的谷歌搜索,我也无法解决。

任何帮助表示赞赏。

编辑

此代码段不属于 Activity 类,所以我没有context对象或getResources()getApplicationContext()...

编辑2(解决方案):

public class PieChartDemo01View extends View 
{
public PieChartDemo01View(Context context) 
{
    super(context);
    Drawable drawable = super.getResources().getDrawable(
        R.drawable.bg2);
    BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;

}
}
4

6 回答 6

2
view.setBackgroundImage(getResources().getDrawable(R.drawable.imgbg))
于 2012-12-06T13:24:55.143 回答
1

试试这个 :

view.setImageResource(R.drawable.imgbg);

更新 :

Drawable imgbg = context.getResources().getDrawable( R.drawable.imgbg );
view.setBackgroundImage(imgbg);
于 2012-12-06T13:18:39.267 回答
1

试试这个:

view.setBackgroundResource(R.drawable.imgbg);
于 2012-12-06T13:21:55.990 回答
1

通过资源 id 获取 Drawable 并在您的方法中使用它:

Drawable drawable = context.getResources().getDrawable(R.drawable.imgbg)
于 2012-12-06T13:21:55.990 回答
1

也许将其更改为

BitmapDrawable background = new BitmapDrawable(BitmapFactory.decodeResource(getResources(),R.drawable.imgbg)) setBackgroundImage(background);

那应该可以工作。

于 2012-12-06T13:29:28.700 回答
1

简单 首先获取drawable,然后在bitmapDrawable 中设置cast。

Drawable drawable=getApplicationContext().getResources().getDrawable(R.drawable.imgbg);
            BitmapDrawable bitmapDrawable=(BitmapDrawable) drawable;

Just Do It 亲爱的它的工作。

于 2012-12-06T14:16:26.740 回答