In this tutorial, we’ll implement ListView in our Android apps using Kotlin.
在本教程中,我们将使用Kotlin在Android应用程序中实现ListView。
什么是Android ListView? (What is Android ListView?)
ListView is a very common UI element in Android Applications. It is used to display a list of items separated by dividers that can be scrolled endlessly. It’s generally used to display a group of related items.
ListView是Android应用程序中非常常见的UI元素。 它用于显示由分隔符分隔的项目列表,可以无限滚动。 通常用于显示一组相关项目。
ListView XML布局 (ListView XML Layout)
<ListView
android:id="@+id/recipe_list_view"
android:layout_width="match_parent"
android:layout_height="wrap_content />
ListView XML属性 (ListView XML attributes)
android:divider
: Drawable or color to draw between list items.android:divider
:可绘制的或可在列表项之间绘制的颜色。android:divider
: Drawable or color to draw between list items.android:divider
:可绘制的或可在列表项之间绘制的颜色。android:dividerHeight
: Height of the divider.android:dividerHeight
:分隔线的高度。android:entries
: An array resource can be passed here to be displayed as a List.android:entries
:可以在此处传递数组资源以显示为列表。android:footerDividersEnabled
: When set to false, there will be no divider at the end of the ListView.android:footerDividersEnabled
:设置为false时,ListView的末尾将没有分隔符。android:headerDividersEnabled
: When set to false, there will be no divider at the top of the ListViewandroid:headerDividersEnabled
:设置为false时,ListView的顶部将没有分隔符android:clickable
: This makes the ListView rows clickable. If you’re setting the ListView from the Activity, setting this attribute is not neccessaryandroid:clickable
:这使ListView行可点击。 如果要从“活动”设置ListView,则无需设置此属性android:listSelector
: Set the background color of the list view row when it is clicked.android:listSelector
:设置单击列表视图行时的背景色。
We can populate entries in the ListView without any Java code by defining an array in the strings.xml
file:
我们可以通过在strings.xml
文件中定义一个数组来填充ListView中的条目而无需任何Java代码:
<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:
现在,ListView在布局中填充为:
<?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 the width to wrap_content wraps the ListView rows to its content.
将宽度设置为wrap_content会将ListView行包装为其内容。
在ListView中设置选择器和分隔线颜色 (Setting Selectors and Divider Color in ListView)
Use the following ListView tag:
使用以下ListView标记:
<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" />
The above code makes the ListView selectable. But to add logic on each ListView row click we need to use the Adapter.
上面的代码使ListView可以选择。 但是要在每个ListView行上添加逻辑,我们需要使用适配器。
ListView适配器 (ListView Adapter)
A ListView class by itself cannot populate the entries. An Adapter is responsible for populating the data in the ListView. We have built-in adapter classes(like the one above) which come with a built-in layout for each row. We can create our own Custom Adapter classes as well.
ListView类本身不能填充条目。 适配器负责填充ListView中的数据。 我们有内置的适配器类(如上面的适配器类),每一行都有内置的布局。 我们也可以创建自己的定制适配器类。
The adapter comes with its own set of built-in methods. Following two are the most important ones:
适配器带有其自己的内置方法集。 以下两个是最重要的:
getView()
: We can inflate our own layouts in the Adapter inside this method.getView()
:我们可以在此方法内的Adapter中增加自己的布局。notifyDataSetChanged()
method on the adapter is called if the data has changed or if new data is available. 如果数据已更改或新数据可用,则调用适配器上的notifyDataSetChanged()
方法。
To set the adapter on the ListView, we use the method setAdapter()
.
要在ListView上设置适配器,我们使用方法setAdapter()
。
ListView适配器的类型 (Types of ListView Adapters)
There are four main types of Adapters:
适配器有四种主要类型:
- BaseAdapter – As the name suggests this abstract is extended by all the other adapters. When creating a custom adapter using this as the parent class, you need to override all the methods mentioned above along with
getCount()
,getId()
etc. BaseAdapter –顾名思义,此抽象被所有其他适配器扩展。 使用此方法作为父类创建自定义适配器时,您需要覆盖上述所有方法以及getCount()
,getId()
等。 - ArrayAdapter – This populates the ListView with the array supplied. 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 rows.
The layout must have a TextView. The third parameter is the array.For the ArrayAdapter you need to override the
ArrayAdapter –使用提供的数组填充ListView。 它定义为:getView()
method only. getCount() isn’t necessary since ArrayAdapter calculates the size of the array on its own.第一个参数是上下文,其后是列表行的布局资源。
布局必须具有TextView。 第三个参数是数组。对于ArrayAdapter,您只需要重写
getView()
方法。 由于ArrayAdapter自行计算数组的大小,因此不需要getCount()。 - ListAdapter – Unlike an ArrayAdapter, this is an interface. So it can be used only with concrete adapter classes. Concrete Adapter classes are ListActivity and ListFragment. ListAdapter –与ArrayAdapter不同,这是一个接口。 因此,它只能与具体的适配器类一起使用。 具体的适配器类为ListActivity和ListFragment。
- SimpleCursorAdapter – This is used when the data needs to populated from a Database. In its constructor, we must specify the layout for each row and also the Cursor instance which contains the fields that need to be displayed. SimpleCursorAdapter –需要从数据库填充数据时使用。 在其构造函数中,我们必须为每一行指定布局,还必须指定包含需要显示的字段的Cursor实例。
ListView Kotlin项目结构 (ListView Kotlin Project Structure)
1. XML布局代码 (1. XML Layout Code)
The code for the activity_main.xml
layout is given below:
下面给出了activity_main.xml
布局的代码:
<?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>
2.主要活动Kotlin代码 (2. Main Activity Kotlin Code)
The code for the MainActivity.kt class is given below.
MainActivity.kt类的代码如下。
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<string>(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 arrived at that shorthand Toast function by adding the Anko commons dependency in our build.gradle
.
在上面的代码中,我们显示一条敬酒消息。 我们通过在build.gradle
添加build.gradle
commons依赖项来实现该简短的Toast函数。
resources.getStringArray(R.array.Colors)
converts the string array stored in the resources file into a Kotlin Array.
resources.getStringArray(R.array.Colors)
将存储在资源文件中的字符串数组转换为Kotlin Array。
android.R.layout.simple_list_item_1 is a built-in layout which hosts a TextView only.
android.R.layout.simple_list_item_1是仅托管TextView的内置布局。
setOnItemClickListener
is the Kotlin function that gets triggered when any ListView row is clicked. Here we can implement our logic.
setOnItemClickListener
是Kotlin函数,当单击任何ListView行时会触发该函数。 在这里,我们可以实现我们的逻辑。
The four arguments inside the function are:
函数内部的四个参数是:
adapterView
: The parent view where the selection happens. Its ListView here.adapterView
:选择发生的父视图。 它的ListView在这里。view
: The selected view (row) within the ListViewview
:ListView中的选定视图(行)position
: The position of the row in the adapter. This is an Int.position
:行在适配器中的位置。 这是一个Int。id
: The row id of the selected item. This is a Long.id
:所选项目的行ID。 这是一个长。
Instead of retrieving the value using the array, we can get it from the adapterView as:
不用使用数组检索值,我们可以通过以下方式从adapterView获取它:
val selectedString = adapterView.getItemAtPosition(position) as String
getItemAtPosition
returns the List View Row at that index. The row is a TextView in this case.
getItemAtPosition
返回该索引处的列表视图行。 在这种情况下,该行是TextView。
The output of the application in action is given below:
实际应用程序的输出如下:
We can change the default item press color by creating a selector drawable inside the drawable folder.
我们可以通过在drawable文件夹内创建一个可绘制的选择器来更改默认项目按色。
list_selector.xml
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 attribute inside the ListView XML Tag:
在ListView XML标记内添加以下属性:
android:listSelector="@drawable/list_selector"
You can download the project from the below link.
您可以从下面的链接下载项目。
翻译自: https://www.journaldev.com/394/android-listview-using-kotlin