android - 如何在 Kotlin 的 fragment 中制作图像列表?

标签 android kotlin

我是 Kotlin 和 Android 开发的新手,我想制作一个具有 ImageViews 的 ListView 的 fragment ,但由于某些奇怪的原因,我收到一条错误消息:

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 并将图像设置到此组件中。在方法结束时返回布局作为结果。如果你有任何问题,你可以问。请检查这个网址:https://demonuts.com/android-listview-kotlin/

关于android - 如何在 Kotlin 的 fragment 中制作图像列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72262882/

相关文章:

android - 除了 Listview 之外,还有其他替代方法可以在 Android 中显示 MySQL 服务器数据吗?

android - Material 设计 : Button or Edit Text?

java - 无法在离线模式下构建 Android Hello World 应用程序

kotlin - 喷气背包组合中给定背景错误的 'on' 颜色冲突

unit-testing - 从函数返回匿名对象并在 Kotlin 中推断类型

java - 手动更改进度条颜色

Android - 移动网络设置菜单(Jelly Bean)

java - Android - 创建进度对话框

kotlin - 合并 map 列表(字符串列表)

kotlin - 在 Kotlin 中使用相同的 try-catch 包装所有内部方法