我在可繪製文件夾中有很多圖標,並且我將它們的名稱設置爲字符串。如何訪問可繪製文件夾並更改背景imageView(或任何視圖)動態使用這些名稱。由於如何將字符串轉換爲可繪製
回答
這是可以做到使用反射:
String name = "your_drawable";
final Field field = R.drawable.getField(name);
int id = field.getInt(null);
Drawable drawable = getResources().getDrawable(id);
或者使用Resources.getIdentifier()
:
String name = "your_drawable";
int id = getResources().getIdentifier(name, "drawable", getPackageName());
Drawable drawable = getResources().getDrawable(id);
然後用這個在任何情況下設置繪製:
view.setBackground(drawable)
如果你有文件名作爲字符串,你可以使用:
int id = getResources().getIdentifier("name_of_resource", "id", getPackageName());
與此ID,您可以訪問它像往常一樣(假定它是一個繪製):
Drawable drawable = getResources().getDrawable(id);
'id'在這種情況下不起作用。 –
謝謝。這個答案是正確的 –
這是可以做到像這樣:
ImageView imageView = new ImageView(this);
imageView.setBackground(getResources().getDrawable(getResources().getIdentifier("name","id",getPackageName())));
謝謝。這個答案也對 –
試試這個:
public Bitmap getPic (int number)
{
return
BitmapFactory.decodeResource
(
getResources(), getResourceID("myImage_" + number, "drawable", getApplicationContext())
);
}
protected final static int getResourceID
(final String resName, final String resType, final Context ctx)
{
final int ResourceID =
ctx.getResources().getIdentifier(resName, resType,
ctx.getApplicationInfo().packageName);
if (ResourceID == 0)
{
throw new IllegalArgumentException
(
"No resource string found with name " + resName
);
}
else
{
return ResourceID;
}
}
謝謝。我相信這是真的,但我沒有嘗試:) –
int resId = getResources().getIdentifier("your_drawable_name","drawable",YourActivity.this.getPackageName());
Drawable d = YourActivity.this.getResources().getDrawable(resId);
謝謝。這個答案也是正確的 –
使用cas e如果沒有任何活動,使用@FD_例子
注:
,如果你是不是在你必須發送上下文PARAM才能使用的任何活動「getResources()」或「getPackageName()」,和「getDrawable(id)」已棄用,請改用getDrawer(int id,主題主題)。 (主題可爲空):
String name = "your_drawable";
int id = context.getResources().getIdentifier(name, "drawable",
context.getPackageName());
Drawable drawable = context.getResources().getDrawable(id, null);
- 1. 將字符串轉換爲可繪製的
- 2. 如何將可繪製的轉換轉換爲可繪製或位圖
- 3. 如何將數字字符串轉換爲數字(十進制)並將數字轉換爲字符串
- 4. 將字符串轉換爲畫布繪製的參考點
- 5. 如何將字符串的字符串轉換爲字符?
- 6. 將IA5String強制轉換爲字符串
- 7. 將字符串轉換爲二進制
- 8. 將字符串轉換爲十進制
- 9. 將字符串轉換爲二進制
- 10. 將二進制轉換爲字符串
- 11. 將字符串轉換爲二進制
- 12. 如何將字符串轉換爲字符串包含十六進制字符
- 13. 將字符串轉換爲字符串
- 14. 將字符串轉換爲字符串
- 15. 將字符串轉換爲字符串
- 16. 如何將字符串轉換爲UInt32?
- 17. 如何將字符串轉換爲UTF8?
- 18. 如何將字符串轉換爲long
- 19. 如何將字符串轉換爲xml
- 20. 如何將OutputStream轉換爲字符串?
- 21. 如何將字符串轉換爲Guid
- 22. 如何將Ada.Real_TIme.Time轉換爲字符串?
- 23. 如何將BeautifulSoup.ResultSet轉換爲字符串
- 24. 如何將BigInteger轉換爲字符串?
- 25. 如何將字符串轉換爲DurationFieldType?
- 26. 如何將字符串轉換爲Bytearray
- 27. 如何將字符串轉換爲int
- 28. 如何將字符串轉換爲Int?
- 29. 如何將字符串轉換爲CFMutableString?
- 30. 如何將字符串轉換爲BigInteger?
我應該使用'view.setBackground(drawable)'或'view.setBackgroundResource(id)'或者什麼? –
我編輯了我的答案。 –
非常感謝。這是工作:)所有的答案都是正確的 –