wawanopoulos
wawanopoulos

Reputation: 9804

Android Kotlin : Sort data in adapter and keeping translation

I'm using the following adapter to create a Spinner dropdown. My adapter only display one text for each item. This item is translated. This code works well but at the end the spinner contains values that are not sorted alphabetically.

How can I modify the code to sort the data and keeping the translation ?

Activity.kt:

val spinner: Spinner = findViewById(R.id.units_cars)
val carsArray = resources.getStringArray(R.array.cars_array)
spinner.adapter = CarsDropdownAdapter(this, carsArray)

cars-array.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="units_array">
        <item>CAR_LABEL1</item>
        <item>CAR_LABEL2</item>
        <item>CAR_LABEL3</item>
    </string-array>
</resources>

CarsDropdownAdapter.kt:

class CarsDropdownAdapter(ctx: Context, private val cars: Array<String>) : ArrayAdapter<String>(ctx, 0, cars) {

    override fun getView(position: Int, recycledView: View?, parent: ViewGroup): View {
        return this.createView(position, recycledView, parent)
    }

    override fun getDropDownView(position: Int, recycledView: View?, parent: ViewGroup): View {
        return this.createView(position, recycledView, parent)
    }

    private fun createView(position: Int, recycledView: View?, parent: ViewGroup): View {
        val carLabel = getItem(position)
        val view = recycledView ?: LayoutInflater.from(parent.context).inflate(R.layout.item_car_dropdown, parent, false)

        // Used to get the translation but at the end the spinner contains Data that are not sorted alphabetically !
        view.car_name_dropdown.text = context.getString(parent.context.resources.getIdentifier(carLabel, "string", context?.packageName))

        return view
    }

}

Upvotes: 0

Views: 1226

Answers (2)

Vir Rajpurohit
Vir Rajpurohit

Reputation: 1937

Use the following code :

val spinner: Spinner = findViewById(R.id.units_cars)
val carsArray = resources.getStringArray(R.array.cars_array)
Collections.sort(carsArray)
spinner.adapter = CarsDropdownAdapter(this, carsArray)

Line Collections.sort(carsArray) will sort the array alphabatically.

Upvotes: 0

Juan Cruz Soler
Juan Cruz Soler

Reputation: 8254

You can sort the string array before creating the Adapter:

val spinner: Spinner = findViewById(R.id.units_cars)
val carsArray = resources.getStringArray(R.array.cars_array)
carsArray.sort()
spinner.adapter = CarsDropdownAdapter(this, carsArray)

The sort implementation for Strings sorts them alphabetically

Upvotes: 1

Related Questions