[英]Setting an ImageView from the drawable folder dynamicly
各位開發者好,
我編寫了一個名為 Item 的類。 現在我希望這個“項目”從 drawable 文件夾中獲取構造函數中的圖像。 我已經嘗試以某種方式從 drawable 文件夾中的圖像中獲取 resourceId,但不知道如何,因為現在有這樣的函數imageView.getResourceId()
無論如何這不是最好的解決方案,因為我需要臨時添加從 drawable 到 imageView 的所有圖像,然后獲取 Id。 有沒有辦法解決這個問題?
感謝您的幫助
嘗試這個,
int id = getResources().getIdentifier("yourpackagename:drawable/" + StringGenerated, null, null);
這將返回您要訪問的可繪制對象的 id...然后您可以通過執行以下操作在 imageview 中設置圖像
imageview.setImageResource(id);
解決方案:
只需在java中使用此代碼將可繪制圖像動態設置為ImageView:
your_image_view_object.setImageDrawable(ContextCompat.getDrawable(Your_Activity.this, R.drawable.your_drawable_image));
例如:
imageView.setImageDrawable(ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_profilepic));
就是這樣。 希望能幫助到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.