I have a function like this:
fromColorResAndUrl(@ColorRes int colorRes, String imageUrl)
Now I call it in this way:
fromColorResAndUrl(R.color.blue,
"http://www.example.com/wallpaper.jpg");
You can see it use an external image link.
I want use local image link. so I save 'wallpaper.jpg'
in res/drawable
.
Now I want to know how can put that in the function?
I try file:///android_asset/drawable/wallpaper.jpg
but no success!
Use R.drawable.wallpaper
, as seen on Drawable Resources on Android Developers
Also, if you import drawables, it is recommended to have them scaled for each phone size. I recommend using android-drawable-importer-intellij-plugin , it is really fast and easy to use.
file:///android_asset/...
URL只能在assets
文件夹中找到资源,因此,如果您使用file:///android_asset/drawable/wallpaper.jpg
则必须将wallpaper.jpg
放在assets/drawable/
文件夹,这不是可绘制对象的默认位置。
Strip out the URL string so you only have the name of the file without the extension
String fileName = "wallpaper"
Then get the int resource value:
int imgR = getResources().getIdentifier(fileName, "drawable", getPackageName());
then get your image with: getResources().getDrawable(imgR)
. As an example for an ImageView:
try {
yourImageView.setImageDrawable(getResources().getDrawable(imgR)
} catch (NotFoundException e) {
int defaultR = getResources().getIdentifier(yourfallbackimg, "drawable", getPackageName())
yourImageView.setImageDrawable(getResources().getDrawable(defaultR))
}
Use a try catch just in case you don't have filename being returned, this way you'll have a default image instead of a crash.
EDIT
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.