1

I try to get checked items from my ListView:

 val lvPlayers = findViewById(R.id.ListViewAllPlayers) as ListView;
    lvPlayers.choiceMode = ListView.CHOICE_MODE_MULTIPLE;
    lvPlayers.adapter = adapter

    lvPlayers.setOnItemClickListener { 
            adapterView: AdapterView<*>, view1: View, i: Int, l: Long ->
        Toast.makeText(applicationContext,lvPlayers.checkedItemCount.toString(),
                Toast.LENGTH_SHORT).show();
        var checked = lvPlayers.checkedItemIds;
        SharedData.SelectedPlayers.clear();
        for (ch in checked) {
            SharedData.SelectedPlayers.add(players.get(ch.toInt()));
        }
    }

But it does not work for me.
I tried to use the code from this question, but as I understand, Kotlin can not iterate over SparseBooleanArray.

So, can you help me to get checked ids of ListView?
Should I somehow create an extension method to iterate over SparseBooleanArray? Or, maybe some other way?

Community
  • 1
  • 1
Admiral Land
  • 2,304
  • 7
  • 43
  • 81

2 Answers2

3

You can iterate over the array by its index with:

for (i in 0..a.size()-1) {
    //access to a[i]
}

See also ranges and for loop

Edited 27th March 2017:

You can use also Collection<*>.indices that is the equivalent

for (i in a.indices) {
    //access to a[i]
}
crgarridos
  • 8,758
  • 3
  • 49
  • 61
1

i understand, Kotlin can not iterate over SparseBooleanArray

Kotlin's for can iterate through anything, if it provides iterator(), be it a method or an extension function. Here are the details.

You can implement SparseBooleanArray#iterator as an extension function and have you code working.

voddan
  • 31,956
  • 8
  • 77
  • 87