[英]How to draw specific drawable resource programmatically?
我的可繪制資源中有一組圖像。 現在,我希望能夠以編程方式使用image.setImageResource(R.id.name_of_image)
相應地更改占位符圖像。
我的ImageView定義為ImageView image = findViewById(R.id.placeholder);
我該怎么做? 我已經嘗試過getIdentifier
但是沒有用。
圖像的格式為Name.jpg
編輯:
我目前有以下構造:
int resID = getResources().getIdentifier(name.toLowerCase(), "drawable", this.getPackageName());
ImageView image = findViewById(R.id.placeholder);
image.setImageResource(resID);
我已將圖片名稱更改為小寫,現在它是一個png文件。
您的圖片必須為png格式(Android首選),並且必須僅包含小寫字母和數字([a-z0-9_。]。然后您可以使用
image.setImageResource(R.drawable.name_of_image);
您可以通過以下方式獲取可繪制的名稱:
String name = context.getResources().getResourceEntryName(R.drawable.name_of_image);
要獲取具有字符串名稱的drawable:
int id = context.getResources().getIdentifier("name_of_image", "drawable", context.getPackageName());
image.setImageResource(id);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.