Use of Android Kotlin ListView

ListView is a very common UI element in Android applications. It is used to display a list of items separated by separators, with infinite scrolling. It is typically used to display a group of related items.

Add ListView to layout:

<ListView
  android:id="@+id/recipe_list_view"
  android:layout_width="match_parent"
  android:layout_height="wrap_content />

The following are the key XML properties used in ListView:
android:divider : Drawable or color between list items.
android:dividerHeight: The height of the divider.
android:entries: Array resources can be passed here to be displayed as a List.
android:footerDividersEnabled: When set to false, there is no separator at the end of the ListView.
android:headerDividersEnabled: When set to false, there will be no separator at the top of the ListView
android:clickable: This makes the ListView rows clickable. You don't need to set this property if you are setting the ListView from an Activity
android:listSelector: set the background color when a list view row is clicked.

By defining the array in the strings.xml file, we can populate the items in the ListView without any Java code:

 <string-array name="Colors">
        <item name="color">Red</item>
        <item name="color">Orange</item>
        <item name="color">Yellow</item>
        <item name="color">Green</item>
        <item name="color">Blue</item>
        <item name="color">White</item>
        <item name="color">Black</item>
        <item name="color">Purple</item>
        <item name="color">Pink</item>
        <item name="color">Gray</item>
        <item name="color">Cyan Blue</item>
        <item name="color">Magenta</item>
    </string-array>

Now the ListView is populated in the layout as:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:entries="@array/Colors"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

Setting width to wrap_content will wrap the ListView rows into its content.

Here's how it appears on the screen:

Insert image description here

Set selector and divider colors

Use the following ListView markup:

<ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:divider="@color/colorPrimary"
        android:dividerHeight="1dp"
        android:entries="@array/Colors"
        android:listSelector="@android:color/holo_green_dark"
        android:clickable="true"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

Insert image description here
The above code makes the ListView selectable. But to add logic on each ListView row click we need to use an adapter.

adapter

The ListView class itself cannot populate entries. The adapter is responsible for populating the data in the ListView. We have built-in adapter classes (as mentioned above) with built-in layout for each row. We can also create our own custom adapter class.

Adapters have their own set of built-in methods. The following two are the most important:

getView(): We can extend our own layout in the adapter in this method.
notifyDataSetChanged()If the data has changed or new data is available, methods on the adapter are called.

To set the adapter on the ListView we use this method setAdapter().

Type of adapter

There are four main types of adapters:

BaseAdapter − As the name suggests, this abstract is extended by all other adapters. When creating a custom adapter using this as a parent class, you need to override all the methods mentioned above getCount(), getId()etc.

ArrayAdapter - Populates the ListView with the provided array. It is defined as:

var arrayAdapter = ArrayAdapter<String>(context,layout,array);

The first parameter is the context, followed by the layout resource for the list row.
The layout must have a TextView. The third parameter is an array.

For ArrayAdapter you just need to override this getView()method. Because the ArrayAdapter calculates the size of the array itself, it is not needed getCount().

ListAdapter − Unlike ArrayAdapter, this is an interface. Therefore it can only be used with concrete adapter classes. The specific adapter classes are ListActivity and ListFragment.

SimpleCursorAdapter - used when data needs to be populated from the database. In its constructor, we must specify the layout of each row and the Cursor instance containing the fields that need to be displayed. We'll look at this issue when we get to databases.

Project structure

Insert image description here

code

activity_main.xmlThe layout code is as follows:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:entries="@array/Colors"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

MainActivity.ktThe code of the class is as follows:

package net.androidly.androidlylistview

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.ArrayAdapter
import kotlinx.android.synthetic.main.activity_main.*
import org.jetbrains.anko.toast

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        var colorArrays = resources.getStringArray(R.array.Colors)
        var arrayAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, colorArrays)

        listView.adapter = arrayAdapter

        listView.setOnItemClickListener { adapterView, view, position: Int, id: Long ->

            toast(colorArrays[position])
        }
    }
}

In the above code, we display a toast message. We achieve this shorthand Toast functionality by adding the Anko commons dependency to build.gradle.

resources.getStringArray(R.array.Colors) Converts an array of strings stored in a resource file to a Kotlin array.

android.R.layout.simple_list_item_1 is a built-in layout that only hosts TextView

setOnItemClickListener is a Kotlin function triggered when any ListView row is clicked. Here we can implement the four parameters within our logical function which are:

adapterView: The parent view where selection occurs. Its ListView is here.
view: The selected view (row) in the ListView
position: The position of the row in the adapter. This is an Int.
id: Row ID of the selected item. This is very long.
Instead of using an array to retrieve the value we can get it from the adapterView:

val selectedString = adapterView.getItemAtPosition(position) as String

getItemAtPositionReturns the list view row at this index. In this case, the row is a TextView.

The output of the actual application is as follows:
Insert image description here
We can change the default item's by-color by creating a drawable selector in the drawable folder.
list_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@color/colorAccent" android:state_pressed="true"/>
    <item android:drawable="@android:color/transparent"/>

</selector>

Add the following attributes inside the ListView XML tag:

android:listSelector="@drawable/list_selector"

Insert image description here

Guess you like

Origin blog.csdn.net/lojloj/article/details/99354864