2012-06-02 78 views
1

我在資源文件夾中有200個圖像,我將它們命名爲name_1.png,name_2.png。我有一個數組,我有幾個數字,如2, 4 , 6 ,30 , 40 ... and so on如何從資源文件夾加載圖像到Android列表視圖

我想將圖像和文本視圖加載到android並根據資源文件夾中的數字顯示圖像。

爲此我創建了一個activity classimage adapter classcustom list view

我可以根據陣列數據編號顯示text view數據,但不顯示圖像。

任何人都可以告訴我該怎麼做。我在想,我必須編寫代碼getview方法來更改圖像。

這是getview方法,我試圖

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 
    convertView = mInflater.inflate(mViewResourceId, null); 


    TextView tv1 = (TextView)convertView.findViewById(R.id.tvtype); 
    TextView tv2 = (TextView)convertView.findViewById(R.id.tvnumber); 
    ImageView i1= (ImageView)convertView.findViewById(R.id.ivlfirst); 
    //int i = Integer.parseInt("normal_"+mStrings.get(position)+".png"); 

i1.setBackgroundResource("normal_"+mStrings.get(position)+".png"); 
    tv1.setText(mStrings1.get(position)); 
    tv2.setText(mStrings.get(position)); 
    return convertView; 
} 
+0

資源文件夾中的'res/drawable /'對嗎? –

+0

是的,它是在res/drawable/ – MADDY

+0

請make image數組。 –

回答

0

你不能輕易做,當您的圖片在res文件夾,因爲每個資源由一個int ID訪問。

您應該考慮將您的圖像放置到您可以像常規文件系統一樣訪問的資產文件夾中。看看AssetManager。

+0

好吧先生我已經將我的圖像到資產文件夾現在我怎麼顯示,你能告訴我一些代碼先生 – MADDY

0

試試這個,如果你想從assets獲取圖像:

InputStream is = ctx.getAssets().open("normal_"+mStrings.get(position)+".png"); 
Drawable d = Drawable.createFromStream(is, "resourceName"); 
i1.setBackgroundDrawable(d); //i1 is your imageView 

希望它幫助!

+0

我得到一個空指針異常 – MADDY

0

它是簡單的只是做在你getView如下()方法

String yourimagename="normal_"+ mStrings.get(position); // In this no need of image extension like .png,.jpg etc 

int resImgId= YourActivityName.this.getResources().getIdentifier("Your Package Name:drawable/" +yourimagename, null, null); 

或試試這個

int resImgId= YourActivityName.this.getResources().getIdentifier("Your Package Name:drawable/" +yourimagename, null, null); 

或試試這個

int resImgId= context.getResources().getIdentifier("Your Package Name:drawable/" +yourimagename, null, null); 
i1.setImageResource(resImgId); 
+0

相同的錯誤兄弟錯誤是:方法getResources()是未定義的類型ImageAndTextAdapter – MADDY

+0

mStrings.get(位置)它返回什麼字符串值或整數值和加入http://chat.stackoverflow.com/rooms/11936/android-lite討論,我們將討論更多,而不是評論 – Khan

+0

請檢查這個洞代碼在paste.org/50002 – MADDY

0

如果你想根據其名稱使用可繪製文件夾中的圖像(從r獲取資源ID esource名)使用公衆詮釋getIdentifier(字符串名稱,字符串DEFTYPE,字符串defPackage)它返回一個資源標識符爲給定的資源名稱,如:

int image = getResources().getIdentifier(image_name, "drawable",getPackageName()); 
ImageView i1= (ImageView)convertView.findViewById(R.id.ivlfirst); 
i1.setBackgroundResource(image); 

您的特定情況下,你可以使用:

i1.setBackgroundResource(getResources().getIdentifier("normal_"+mStrings.get(position), "drawable",getPackageName())); 
+0

@MADDY讓我知道它是否適用於你:) –

0

採取一Integer arrayR.drawable.imageView1......200,並通過它的價值就像

private Integer[] Imgid = {R.drawable.imageview1,....,200 }; 
    i1.setBackgroundResource(Imgid[j]); 
相關問題