繁体   English   中英

如何从Drawable接收链接?

[英]How can I receive link from Drawable?

我有一个这样的功能:

 fromColorResAndUrl(@ColorRes int colorRes, String imageUrl)

现在,我以这种方式称呼它:

fromColorResAndUrl(R.color.blue,
                 "http://www.example.com/wallpaper.jpg");

您可以看到它使用外部图像链接。

我想使用本地图像链接。 所以我将'wallpaper.jpg'保存在res/drawable

现在我想知道如何将其放入函数中?

我尝试file:///android_asset/drawable/wallpaper.jpg但没有成功!

使用R.drawable.wallpaper ,如Android Developers上的Drawable Resources所示

另外,如果导入可绘制对象,则建议针对每个电话尺寸缩放它们。 我建议使用android-drawable-importer-intellij-plugin ,它确实快速且易于使用。

file:///android_asset/... URL只能在assets文件夹中找到资源,因此,如果您使用file:///android_asset/drawable/wallpaper.jpg则必须将wallpaper.jpg放在assets/drawable/文件夹,这不是可绘制对象的默认位置。

去除URL字符串,以便仅使用文件名而不使用扩展名

String fileName = "wallpaper"

然后获取int资源值:

int imgR = getResources().getIdentifier(fileName, "drawable", getPackageName());

然后使用以下代码获取图像: getResources().getDrawable(imgR) 以ImageView为例:

try {

    yourImageView.setImageDrawable(getResources().getDrawable(imgR)
    } catch (NotFoundException e) {
        int defaultR = getResources().getIdentifier(yourfallbackimg, "drawable", getPackageName())
        yourImageView.setImageDrawable(getResources().getDrawable(defaultR))
    }

如果没有返回文件名,请使用try catch,这样您将拥有默认图像而不是崩溃。

编辑

检查http://pastebin.com/yN3zUciN

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM