首页 > 解决方案 > 如何在android [kotlin]中获取图像的resourceId?

问题描述

我正在尝试使用自定义适配器(没有视图支架)创建一个列表视图。我想将图像插入到我的自定义列表视图中。

我最终得到了这行代码:

class CategoryAdapter(context: Context, categories: List<Category>) : BaseAdapter(){

val context = context
val categories = categories

override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
    val categoryView: View

    categoryView = LayoutInflater.from(context).inflate(R.layout.category_list_item, null)
    val categoryImage : ImageView = categoryView.findViewById(R.id.imageView2)
    val categoryName : TextView = categoryView.findViewById(R.id.textView2)

    val category = categories[position]


    val resourceId = context.resources.getIdentifier(category.image, "drawable", context.packageName)
    categoryImage.setImageResource(resourceId)
    categoryName.text = category.title

    return categoryView
}

override fun getItem(position: Int): Any {
    return categories[position]

}

override fun getItemId(position: Int): Long {
    return 0
}

override fun getCount(): Int {
    return categories.count()
}}

这完全正常。我对以下行的工作方式一无所知。

  val resourceId = context.resources.getIdentifier(category.image, "drawable", context.packageName)

你能解释一下这段代码吗?

标签: androidlistviewkotlin

解决方案


你想使用:

在 Android 中动态检索资源

通常,在代码中检索资源(可绘制对象、字符串、你有什么)时,您使用自动生成的 R.java 来执行此操作。但是,我最近在我的应用程序中,其中一个 ImageView 中的项目旁边有一个不同的图标。所有这些的数据都存储在可绘制的图像中,这意味着我无法将我的数据链接到 R.java。尽管如此,我还是需要一些方法来通过名称来获取 Drawable,所以我首先求助于getResources().getIdentifier(). 此方法可以很好地在任何包中找到您想要的任何资源 id:

基于这个博客

喜欢 :

if (cnt == 7) {
    cnt = 1;
}
int resID = getResources().getIdentifier("ad_banner" + cnt, "drawable", getPackageName());
activityTwillioCallBinding.imgAdView.setImageResource(resID);
cnt++;

这一切都很好。

基于此文档https://developer.android.com/reference/android/content/res/Resources.html#getIdentifier(java.lang.String,%20java.lang.String,%20java.lang.String)

获取资源()

返回应用程序包的资源实例。

public int getIdentifier(字符串名称、字符串 defType、字符串 defPackage)

返回给定资源名称的资源标识符。完全限定的资源名称的格式为“package:type/entry”。如果此处分别指定了 defType 和 defPackage,则前两个组件(包和类型)是可选的。

注意:不鼓励使用此功能。按标识符检索资源比按名称检索资源效率更高。

参数

name String:所需资源的名称。

defType String:如果名称中不包含“type/”,则要查找的可选默认资源类型。可以为 null 以要求显式类型。

defPackage 字符串:如果名称中不包含“package:”,则要查找的可选默认包。可以为 null 以要求显式包。

返回 int int 关联的资源标识符。如果没有找到这样的资源,则返回 0。(0 不是有效的资源 ID。)


推荐阅读