2012-02-11 80 views
0

我有以下问题:使用字符串来更改位图

String explosion_type = this.prefs.getString("explosion_type", "ring_explosion"); 

    BitmapFactory.Options optionsExplosion = new BitmapFactory.Options(); 
    optionsExplosion.inPurgeable = true; 
    this._explosionSprite = BitmapFactory.decodeResource(_context.getResources(), 
com.forwardapps.liveitems.R.drawable.explosion, optionsExplosion); 

我试图在地方资源名称的使用字符串,这样我可以在首选项菜单资源热插拨。此方法导致应用程序崩溃。

实现这种情况的正确方法是什么? (没有使它过于复杂或使用的if语句)

回答

0

使用方法则getIdentifier上的资源对象的可绘制的获取ID:

String explosion_type = this.prefs.getString("explosion_type", "ring_explosion"); 
    Log.i("imagename", explosion_type); 
    BitmapFactory.Options optionsExplosion = new BitmapFactory.Options(); 
    optionsExplosion.inPurgeable = true; 

    int imageResource = getResources().getIdentifier(explosion_type, "drawable", getPackageName()); 

     this._explosionSprite = BitmapFactory.decodeResource(_context.getResources(), imageResource, optionsExplosion); 
+0

谢谢你,我给这个一杆。 – 2012-02-11 11:24:53

+0

您的应用程序包,替换为“yourpackage” – jeet 2012-02-11 11:31:47

+0

这样? \t \t int imageResource = _context.getResources()。getIdentifier(explosion_type,null,_context.getPackageName()); \t this._explosionSprite = BitmapFactory.decodeResource(_context.getResources(),imageResource,optionsExplosion); – 2012-02-11 11:33:56