如何在 Kotlin 的片段中制作图像列表?

How to make a list of images in a fragment in Kotlin?

我是 Kotlin 和 Android 开发的新手,我想制作一个包含 ImageView 的 ListView 的片段,但出于某种奇怪的原因,我收到一条错误消息:

java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView

这是我的 Fragment.kt 代码

var array = arrayOf(
        R.drawable.serbia,
        R.drawable.croatia,
        R.drawable.bulgaria,
        R.drawable.azerbejdzan,
        R.drawable.hungari)

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val context = context as MainActivity

        val lv = context.findViewById(R.id.listview_1) as ListView

        val adapter = ArrayAdapter(context, R.layout.simple_list_item_1, R.id.image1, array)
        lv.adapter = adapter
}

这是我的 simple_list_item_1.xml

<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/image1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dip"
    tools:ignore="ContentDescription">
</ImageView>

我使用字符串列表和 TextView 制作了它,效果很好,但我似乎无法弄清楚如何使用图像来完成它。有什么建议吗?

您应该创建从 BaseAdapter 扩展而来的新 CustomAdapter,并且此适配器应该将数组、上下文作为构造函数中的参数。您应该实现此适配器的 getView 方法并使用此方法内的布局。使用 findViewById 方法从此布局中查找 imageview 并将图像设置到此组件中。在方法 return 布局的末尾作为结果。如果你有任何问题,你可以问。请检查这个 url : https://demonuts.com/android-listview-kotlin/