What is a List View?
Android List View is a ViewGroup which displays the items on screen in a list. The List View contains an adapter which fetches the data from the list and displays it on the screen. The List View is preferable for a list of 50 items. If the Numbers are being exceeded, Kindly use Recycler view as it consumes less resources.
Lets create a List View in our main activity xml file. Go to Palette > Legacy. Drag and drop List view to component tree. Select the list view and rename it's id to somewhat cities or anything.
Explanation to the Code:
So, here first we create an array of Strings which has names of city in japan.
Next we will get the id from layout file and define it's type in code. Previously in XML file we defined cities as our list view. So, we have reference to list view in val city.
Creating an adapter : Adapter is a bridge between the data and view. Our variable city Names is a type of an array. we will use array adapter.
In array arguments, we pass context, and system built layout (android.R.layout.simple_list_item_1). You can play around with this system layout and select whichever suits best to your requirement.
Now link adapter to view.
That is it. You Just created a list view in kotlin.
You can add a little more functionality, i.e a toast on click of any of the items inside the list by following the code given above.
Google has launched JetPack which does not require to create a layout in XML file. Need to Learn more about the Android JetPack Components click here.
I tried making it the simplest possible. Do share with your friends if they also need it. Keep coding.
Comments