2012-02-11 60 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