ListView 和自定义适配器在 Kotlin 中不起作用

ListView & Custom Adapter dont work Kotlin

我不明白为什么列表没有在自定义适配器的帮助下填充。只有数组中的最后一个元素进入 textView (textHeroView)。事实证明,ListView 不是作为列表,而是仅包含数组中的一项。我试图将它放在一个单独的列表中,但无济于事。你能告诉我我做错了什么吗?

HeroesAdapter

class HeroesAdapter(context: Context, heroes: List<TestHero>): BaseAdapter() {
    private val context = context
    private val heroes = heroes

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

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

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

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

           // categoryView = LayoutInflater.from(context).inflate(R.layout.activity_heroes, null)
        val listheroView = LayoutInflater.from(context).inflate(R.layout.list_hero_view, parent, false)
           // val categoryImage: ImageView = categoryView.findViewById(R.id.heroesImageView)
            val heroText: TextView = listheroView.findViewById(R.id.textHeroView)
            val category = heroes[position]

           // heroText.text = category.legends.all.keys.first()
        for((key) in category.legends.all){
            Log.d("HeroesActivity", key)
            heroText.text = key
        }

            return listheroView

    }
}

list_hero_view

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <ImageView
        android:id="@+id/heroesImageView"
        android:layout_width="426dp"
        android:layout_height="180dp"
        android:layout_marginTop="24dp"
        android:scaleType="centerCrop"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.533"
        app:layout_constraintStart_toStartOf="parent"
        app:srcCompat="@mipmap/wraith_apex_legends" />

    <TextView
        android:id="@+id/textHeroView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Wraith"
        android:textColor="@android:color/darker_gray"
        android:textSize="54sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="@+id/heroesImageView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.12"
        app:layout_constraintStart_toStartOf="@+id/heroesImageView"
        app:layout_constraintTop_toTopOf="@+id/heroesImageView"
        app:layout_constraintVertical_bias="0.04000002" />
</androidx.constraintlayout.widget.ConstraintLayout>

activity_heroes

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".HeroesActivity">

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="2dp"
        android:layout_marginTop="2dp"
        android:layout_marginBottom="24dp"
        app:layout_constraintBottom_toTopOf="@+id/heroesListView"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@mipmap/ic_launcher_round" />

    <ListView
        android:id="@+id/heroesListView"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_marginStart="1dp"
        android:layout_marginTop="100dp"
        android:layout_marginEnd="1dp"
        android:layout_marginBottom="1dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textNickname"
        android:layout_width="251dp"
        android:layout_height="29dp"
        android:layout_marginStart="40dp"
        android:layout_marginEnd="279dp"
        android:layout_marginBottom="60dp"
        android:text="Nickname"
        android:textSize="20sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toTopOf="@+id/heroesListView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.145"
        app:layout_constraintStart_toEndOf="@+id/imageView2"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.272" />

    <TextView
        android:id="@+id/textLvl"
        android:layout_width="111dp"
        android:layout_height="19dp"
        android:layout_marginEnd="28dp"
        android:layout_marginBottom="42dp"
        android:text="Lvl"
        app:layout_constraintBottom_toTopOf="@+id/heroesListView"
        app:layout_constraintEnd_toEndOf="@+id/textNickname"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="@+id/textNickname"
        app:layout_constraintTop_toBottomOf="@+id/textNickname"
        app:layout_constraintVertical_bias="0.562" />
</androidx.constraintlayout.widget.ConstraintLayout> 

HeroesActivity

class HeroesActivity : AppCompatActivity() {

    lateinit var heroesAdapt : HeroesAdapter

    val listHero = ArrayList<TestHero>()
    private val TAG = "HeroesActivity"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_heroes)

        getCurrentData()

        val lisView : ListView = findViewById(R.id.heroesListView)

        heroesAdapt = HeroesAdapter(this, listHero)
        lisView.adapter = heroesAdapt
        //heroesListView.adapter = heroesAdapt
        
            // heroesAdapt = HeroesAdapter(this, arrayListOf("a","b","c","d","e","f"));
        // lisView.adapter = heroesAdapt


    }

    private fun getCurrentData() {
        val api = Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(ApiRequest::class.java)

        GlobalScope.launch(Dispatchers.IO) {
            val response = api.herList().awaitResponse()
            if (response.isSuccessful) {
                val data = response.body()!!
                Log.d(TAG, data.toString())

                withContext(Dispatchers.Main){
                   // adapter.add(data.global.name)
                   // adapt.add(data.global.platform)

                    listHero.add(data)
                    heroesAdapt.notifyDataSetChanged()
                    textNickname.text = "${data.global.name} (${data.global.rank.rankDiv} divisions)"
                    textLvl.text = "Level: ${data.global.level.toString()}"
                    when(data.global.rank.rankName){
                        "Silver" -> textNickname.setTextColor(Color.parseColor("#7A7A79"))
                        "Gold" ->   textNickname.setTextColor(Color.parseColor("#E6D600"))
                        "Platinum" -> textNickname.setTextColor(Color.parseColor("#36BBCE"))
                    }

                }

            }
        }
    }
}

我认为问题出在这段代码中

    for((key) in category.legends.all){
        Log.d("HeroesActivity", key)
        heroText.text = key
    }

并记录屏幕

TestHero.kt

data class TestHero (@SerializedName("global") val global: PlayerInf,
                     @SerializedName("legends")val legends: AllLegends)

data class  PlayerInf (val name: String, val uid: Long, val avatar: String, val platform: String,
val  level: Int, val toNextLevelPercent: Int, val internalUpdateCount: Int, val bans: BanInf, val rank: RankInf)

data class BanInf (val isActive: Boolean, val remainingSeconds: Int)

data class RankInf (val rankScore: Int, val rankName: String, val rankDiv: Int, val rankImg: String)


data class AllLegends (@SerializedName("all") val all: Map<String, LegendWrapper> = emptyMap())


data class LegendWrapper(
    val data: List<PlayerPerformance>? = emptyList()

)
data class PlayerPerformance(val name: String, val value: Int, val key: String)

在您的 list_hero_view.xml 中,将高度从匹配父级更改为环绕内容。稍后谢谢我:-P

我没有发现您的代码有任何问题,

试试这个:

设置适配器:

    binding.heroesListView.adapter = HeroesAdapter(applicationContext, arrayListOf("a","b","c","d","e","f"));

适配器:

package com.example.Whosebug

import android.content.Context
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.TextView
class HeroesAdapter(context: Context, heroes: List<String>): BaseAdapter() {
    private val context = context
    private val heroes = heroes

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

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

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

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

        // categoryView = LayoutInflater.from(context).inflate(R.layout.activity_heroes, null)
        val listheroView = LayoutInflater.from(context).inflate(R.layout.item_hero, parent, false)
        // val categoryImage: ImageView = categoryView.findViewById(R.id.heroesImageView)
        val heroText: TextView = listheroView.findViewById(R.id.textHeroView)
        val category = heroes[position]

        heroText.text = category

        return listheroView

    }
}

对于适配器来说,它是一个视图的一个项目。您的支持列表只有一项。 getView() 内的 for 循环正在迭代该单个项目内的一些集合,并一遍又一遍地设置同一个 TextView 的值,直到到达最后一个。

由于您的适配器的支持类型是 TestHero,您的列表视图只能显示每个 TestHero 实例的一个行项目。你只有一个 TestHero 实例。

根据您所展示的内容,无论列表 TestHero.legends.all 是什么类型,您都应该设置适配器的支持类型。在您的协程中,您可以将该列表从您的 TestHero 中拉出并将其传递给您的适配器。您需要使后备列表 属性 可变。

就像我在评论中所说的那样,不要为此使用可变列表。您应该从一个空列表开始。

例如,如果此列表的类型为 Legend,则您的适配器应如下所示:

class HeroesAdapter(): BaseAdapter() {
    var heroes: List<Legend> = emptyList()

    override fun getCount(): Int = heroes.size

    override fun getItem(position: Int): = heroes[position]

    override fun getItemId(position: Int) = position

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        val view = convertView ?: LayoutInflater.from(parent.context).inflate(R.layout.list_hero_view, parent, false)
        val heroText: TextView = view.findViewById(R.id.textHeroView)
        val hero = heroes[position]
        heroText.text = hero.keys.first()
        return view
    }
}

并在您的 Activity 中删除 listHero 属性。在你的协程中,在你得到你的数据之后,做

heroesAdapt.apply {
    heroes = data.legends.all
    notifyDataSetChanged()
}

另外,考虑切换到 RecyclerView。 ListView 有点过时了,我一直希望他们弃用它,因为他们在过去几年只致力于改进 RecyclerView。