android:用getIdentifier()獲取資源Id


項目中一問題,從獲取圖片名稱后,然后調用圖片。直接用R.drawable.?無法調用。解決:

主要由兩種方法,個人建議第二種。 
1. 不把圖片放在res/drawable下,而是存放在src某個package中(如:com.drawable.resource),這種情況下的調用方法為: 
String path = "com/drawable/resource/imageName.png"; 
InputStream is = getClassLoader().getResourceAsStream(path); 
Drawable.createFromStream(is, "src"); 

2. 如果還是希望直接使用res/drawable中的圖片,就需要通過下面的方法了: 
假設創建工程的時候,填寫的package名字為:com.test.image 
int resID = getResources().getIdentifier("imageName", "drawable", "com.test.image"); 
Drawable image = getResources().getDrawable(resID);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM