Kotlin Android Simple ListView Sort Ascending and Descending Example
How to sort a simple listview in ascending and descending manner in Kotlin Android.
Let’s see how to sort data in a ListView in both ascending and descendig manner.
You click a button to sort in ascending, then click it again to toggle the sort into descending manner and vice versa.
===
Concepts You will Learn
Here are some of the concepts you will learn from this tutorial.
- What is a ListView?
- What is Data Sorting?
- How to sort a ListView Alphabetically in both ascending and descending manner.
- How to populate a ListView with an Array in Kotlin.
Video Tutorial
Well we have a video tutorial as an alternative to this. If you prefer tutorials like this one then it would be good you subscribe to our YouTube channel, ProgrammingWizards TV. Basically we have a TV for programming where do daily tutorials especially android.
What is Kotlin?
Kotlin is a programming language targeting the Java
platform. Kotlin is concise, safe, pragmatic, and focused on interoperability with Java code.
Kotlin is usble almost everywhere Java is used today – for server-side development, Android apps, and much more.
Kotlin like Java is a statically typed programming language. This implies the type of every expression in a program is known at compile time, and the compiler can validate
that the methods and fields you’re trying to access exist on the objects you’re using.
(a). Defining Packages in Kotlin
Normally classes are organized in packages in Java. This applies to Kotlin as well.
Package specification should be at the top of the source file:
package info.camposha
import java.util.*
class Starter{
...
}
However, be aware that it’s not required to match directories and packages: source files can be placed arbitrarily in the file system.
(b). Defining Functions in Kotlin
Roughly speaking, functions in Kotlin are the equivalent of methods in java.
Functions can take input parameters and can return values. Here’s such a function:
fun sum(a: Int, b: Int): Int {
return a + b
}
This can be condensed into a single line given that it has an expression body and we can infer the retur types:
fun sum(a: Int, b: Int) = a + b
However, if functions do not return any meaningful value:
fun printSum(a: Int, b: Int): Unit {
println("sum of $a and $b is ${a + b}")
}
Demo
Let’s see the full example.
ListView Sort Descending Unsorted ListView ListView Sort Ascending
1. Resources.
Android platform provides a powerful and flexible way of adding static content as a resource.
These static content will also be packaged into the APK file. The static content will be stored either as a resource or as an asset.
Resources belong to a given type. These types can be:
- Drawable.
- Layout.
- Value.
Let’s start by looking at the layout resources
(a). activity_main.xml
This layout will get inflated into the main activity’s user interface. This will happen via the Activity’s setContentView()
method which will require us to pass it the layout.
We will do so inside the onCreate()
method of Activity.
In this case we use the following widgets:
- RelativeLayout – our viewgroup.
- TextView – to render our data.
- Button – To toggle sort order.
- ListView – To render both our sorted and unsorted data.
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout android_layout_width="match_parent" android_layout_height="match_parent" tools_context="info.camposha.kotlinsortsimplelistview.MainActivity"> <TextView android_id="@+id/headerLabel" android_layout_width="wrap_content" android_layout_height="wrap_content" android_layout_alignParentTop="true" android_layout_centerHorizontal="true" android_fontFamily="casual" android_text="Array Sorting ListView" android_textAllCaps="true" android_textSize="24sp" android_textStyle="bold" /> <Button android_id="@+id/mySortBtn" android_layout_width="wrap_content" android_layout_height="wrap_content" android_layout_alignParentBottom="true" android_layout_centerHorizontal="true" android_layout_marginBottom="12dp" android_fontFamily="serif-monospace" android_text="Toggle Sort" /> <ListView android_id="@+id/myListView" android_layout_width="match_parent" android_layout_height="match_parent" android_layout_above="@+id/mySortBtn" android_layout_alignParentEnd="true" android_layout_alignParentRight="true" android_layout_below="@+id/headerLabel" android_layout_marginTop="33dp" /> </RelativeLayout>
2. Kotlin Code
Kotlin is our programming language in this case.
(a) MainActivity.kt
Our main activity.
package info.camposha.kotlinsortsimplelistview
import android.app.Activity
import android.os.Bundle
import android.widget.*
import java.util.*
class MainActivity : Activity() {
private var myListView: ListView? = null
private var mySortButton: Button? = null
private var galaxies = arrayOf("Sombrero", "Cartwheel", "Pinwheel", "StarBust", "Whirlpool", "Ring Nebular", "Own Nebular", "Centaurus A", "Virgo Stellar Stream", "Canis Majos Overdensity", "Mayall's Object", "Leo", "Milky Way", "IC 1011", "Messier 81", "Andromeda", "Messier 87")
private var sortAscending = true
private var galaxiesList = Arrays.asList(*galaxies)
private fun sortData() {
if (sortAscending) Collections.sort(galaxiesList)
else
Collections.reverse(galaxiesList)
sortAscending = !sortAscending
myListView!!.adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, galaxiesList)
myListView!!.onItemClickListener = AdapterView.OnItemClickListener { adapterView, view, i, l -> Toast.makeText(this@MainActivity, galaxiesList[i], Toast.LENGTH_SHORT).show() }
}
private fun initializeViews() {
myListView = findViewById(R.id.myListView)
//with arrayadapter you have to pass a textview as a resource, and that is simple_list_item_1
myListView!!.adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, galaxies)
mySortButton = findViewById(R.id.mySortBtn)
mySortButton!!.setOnClickListener { sortData() }
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
initializeViews()
}
}
3. Download
You can download full source code below.
No. | Location | Link |
---|---|---|
1. | GitHub | Direct Download |
2. | GitHub | Browse |
3. | YouTube | Our YouTube Channel |
2. | YouTube | Watch Video Tutorial |
4. | Camposha | View All ListView Tutorials |