2013-08-04 108 views
0

嘿傢伙我有以下代碼。我基本上是在意圖回憶並根據按下的按鈕生成一個數字,我想要顯示某個圖像。setImageResource從生成文件路徑

Intent intent = getIntent(); 
    int number = intent.getIntExtra("BUTTON NUMBER", 1); 
    ImageView image = (ImageView) findViewById(R.id.imageView); 

    String resource = "R.raw.img" + number; 
    id = Integer.parseInt(resource); 
    image.setImageResource(id); 

然而代碼似乎並不奏效,並出現以下錯誤應用程序崩潰:

E/AndroidRuntime(12872): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapp/com.example.myapp.SecondActivity}: java.lang.NumberFormatException: Invalid int: "R.raw.img1"

任何想法?我以爲我已經allaedy轉換成一個整數的字符串?

回答

0

首先,您不能將「R.raw.img1」解析爲一個整數。這就是爲什麼你在這裏得到java.lang.NumberFormatException

您正在嘗試訪問ID爲「R.raw.img1」的資源 - 這是生成的ID。請參閱項目 - > gen - > [packageName] - > R.java。 所以「R.raw.img1」是生成的id(整數)的名稱。以你試圖做的方式訪問整數,是不可能的。 嘗試

int resID = getResources().getIdentifier("img"+number, "raw", getPackageName()); 

這樣你應該得到正確的ID。

0

嘗試以下操作:

int id = getResources().getIdentifier("android.resource://com.example.myapp/raw/img"+number,null,null); 
img.setImageResource(id); 

Source

0

做這樣的:

Intent intent = getIntent(); 
int number = intent.getIntExtra("BUTTON NUMBER", 1); 
ImageView image = (ImageView) findViewById(R.id.imageView); 

int resID = getResources().getIdentifier("img"+number, "raw", getPackageName()); 
image.setImageResource(resID); 
0
**This is very much simple code and is working fine for me. 
You directly can set Resource with its id to an ImageView as shown below.** 

     "ImageView img=(ImageView) findViewById(R.id.imgView); 
     img.setImageResource(R.raw.calendar); " 


Code: 

package packageName; 

import android.os.Bundle; 
import android.app.Activity; 
import android.view.Menu; 
import android.widget.ImageView; 

public class MainActivity extends Activity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     ImageView img=(ImageView) findViewById(R.id.imgView); 
     img.setImageResource(R.raw.calendar); 

    } 
} 


Thanks..