嵌套循环会多次添加同一元素

时间:2020-10-08 19:25:51

标签: android kotlin arraylist android-recyclerview

我有2个arrays,分别是string-arrayinteger-array,如下所示:

   val country= resources.getStringArray(R.array.country_array)
   val flags = resources.getIntArray(R.array.country_flag_array)

在我的strings.xml中,如下所示:

<string-array name="country_array">
    <item>USA</item>
    <item>France</item>
    <item>Canada</item>

</string-array>

<integer-array name="country_flag_array">
    <item>@drawable/flag_united_states_of_america</item>
    <item>@drawable/flag_france</item>
    <item>@drawable/flag_canada</item>

</integer-array>

我有一个data class来添加国家标志,它的名称是用来填充recyclerView的。

data class CountryObject(val flagImage : Int, val country: String)

我具有使用标记和国家/地区填充list的功能:

private fun addCountriesToList(country: Array<String>, flgs : IntArray) : List<CountryObject>{

        val listCountry= ArrayList<CountryObject>()

        for(c in country){
            for (f in flgs){
                listCountry.add(CountryObject(f,  c))
            }
        }

        return listCountry
    }

编辑:附加代码:

这是我保存addCountriesToList函数的地方

   val listCountry : List<CountryObject> = addCountriesToList(country, flags)

我还有另一个填充回收者视图的功能(据我所知)

setupLanguageList(rv_country, listCountry , 0)

我可以用国家名称填充recyclerView,但是每个国家名称都用数组的大小填充,并且图像不显示。因此,由于有3个国家/地区,因此每个国家/地区填充了3次。

对于为什么这样显示语言而不显示图像的任何帮助或建议,将受到高度赞赏。

2 个答案:

答案 0 :(得分:0)

您正在为每个国家/地区与每个标志添加一次相同的国家/地区。您只需要为每个国家/地区添加匹配的索引标志

val countryObjects = country.indexedMap { index, country ->
    CountryObject(flgs[index], country)
}

此处,映射是一个带有一个参数(一个函数)的迭代器,该结果将构成列表的元素。这里的函数是用lambda语法化的Sugar,参数是当前元素和元素本身的索引。 lambda返回您的CountryObject,因为lambda的最后一个声明是return。

因此在这种情况下,您可以执行此操作,因为您在字符串和整数上都具有该国家/地区的匹配索引。更好的解决方案是枚举。

enum class Country(val flagImage : Int, val country: String) {
    USA(/*the values here*/)
    //the other countries
}

然后您可以像这样Country.values()

直接使用枚举

答案 1 :(得分:0)

嵌套这些循环没有意义,因为您只希望每个循环中的每个元素之一。如果嵌套它们,则将得到的结果数相乘。

解决此问题的方法是按索引迭代一次:

for(i in 0 until min(country.size, flgs.size)) {
    listCountry.add(CountryObject(flgs[i], country[i]))
}

您还可以使用快捷方式:zip函数:

val listCountry = flgs.zip(country) { f, c -> CountryObject(f, c) }

或更简洁地说:

val listCountry = flgs.zip(country, ::CountryObject)
相关问题