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)

<ListViewandroid: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"><ListViewandroid: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标记:

<ListViewandroid: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:

适配器带有其自己的内置方法集。 以下两个是最重要的:

  1. getView() : We can inflate our own layouts in the Adapter inside this method.getView() :我们可以在此方法内的Adapter中增加自己的布局。
  2. 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:

适配器有四种主要类型:

  1. 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()等。
  2. 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 getView() method only. getCount() isn’t necessary since ArrayAdapter calculates the size of the array on its own.

    ArrayAdapter –使用提供的数组填充ListView。 它定义为:

    第一个参数是上下文,其后是列表行的布局资源。
    布局必须具有TextView。 第三个参数是数组。

    对于ArrayAdapter,您只需要重写getView()方法。 由于ArrayAdapter自行计算数组的大小,因此不需要getCount()。

  3. 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。
  4. 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"><ListViewandroid: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.androidlylistviewimport android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.ArrayAdapter
import kotlinx.android.synthetic.main.activity_main.*
import org.jetbrains.anko.toastclass 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 = arrayAdapterlistView.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.

您可以从下面的链接下载项目。

AndroidlyListViewAndroidlyListView

翻译自: https://www.journaldev.com/394/android-listview-using-kotlin

使用Kotlin的Android ListView相关推荐

  1. 第14章 使用Kotlin 进行 Android 开发

    2019独角兽企业重金招聘Python工程师标准>>> 第14章 使用Kotlin 进行 Android 开发 根据Realm Report (2017-Q4,https://rea ...

  2. Kotlin学习之ListView

    Kotlin学习之ListView Kotlin学习之ListView 前言 一.创建xml 二.创建ListView的adapter 三.在mainactivity中设置listview的adapt ...

  3. android ListView包含Checkbox滑动时状态改变

    题外话: 在xamarin android的开发中基本上所有人都会遇到这个小小的坎,的确有点麻烦,当时我也折腾了好一半天,如果你能看到这篇博客,说明你和我当初也是一样的焦灼,如果你想解决掉这个小小的坎 ...

  4. Android ListView 自定义背景后 滚动时的背景变黑问题

    ListView是常用的显示控件,默认背景是和系统窗口一样的透明色,如果给ListView加上背景图片,或者背景颜色时,滚动时listView会黑掉,原因是,滚动时,列表里面的view重绘时,用的依旧 ...

  5. 用Kotlin写Android Gradle脚本

    Android应用开发中,离不开Gradle脚本的构建.大部分Android开发同学忽视了脚本的力量,甚至有很大一部分同学不知道Gradle脚本是什么,用什么语言编写的:当然,也有相当一部分同学知道G ...

  6. Kotlin for Android

    在Google IO 2017 大会上,Google将 Kotlin列为 Android官方开发语言,Android Studio 3.0 也默认集成了Kotlin插件. Android Studio ...

  7. Android listview viewholder

    2019独角兽企业重金招聘Python工程师标准>>> Android ListView ViewHolder 利用adapter中的getView的 contentView 的复用 ...

  8. 如果你现在学Android---学习使用Kotlin进行Android开发

    原文地址: http://www.eoeandroid.com/thread-902176-1-1.html?_dsign=650ea146 之前写了一篇<如果你现在学Android–写给新手的 ...

  9. Android ListView常用用法

    ListView是比较常用的控件,但一直都觉得创建ListView步骤有点繁琐,故在此总结一下,方便查阅. 程序效果是实现一个ListView,ListView里面有标题,内容和图片,并加入点击和长按 ...

最新文章

  1. 快速生成apk 自动发布到网站 便于测试
  2. 处理字符串时常用方法0914
  3. Java 技术篇-借助自定义对象实现函数返回多个不同类型的值实例演示
  4. c语言程序开发中连接是,C语言中等待socket连接和对socket定位的方法
  5. 旁瓣对消原理_雷达天线旁瓣对消技术
  6. CF思维联系– CodeForces - 991C Candies(二分)
  7. python3 while循环语句_python While 循环语句
  8. C#LeetCode刷题之#136-只出现一次的数字(Single Number)
  9. tmp name php,linux环境 上传文件失败 tmp_name为空
  10. 机器学习实践指南(二)—— 正则化参数
  11. java+cache使用方法_JVM代码缓存区CodeCache原理及用法解析
  12. datatable 参数详细说明
  13. Intel APIC Configuration
  14. python中浮点型占几个字节_python的浮点数占多少个字节
  15. ddos是攻击服务器还是网站,服务器遭到DDoS攻击选高防IP还是CDN?
  16. table-responsive响应式表格,手机端表格自适应
  17. ps,pr,3Dmax软件使用经验
  18. 多场景业务实战-AB测试实战(数据分析干货!!!!!)
  19. 奋斗吧,程序员——第三章 平生渭水曲,谁识此老翁
  20. 内存优化总结:ptmalloc、tcmalloc和jemalloc

热门文章

  1. 不可磨灭的记忆 CPU发展史经典回顾
  2. [转载] python字典更新值_Python–字典元组值更新
  3. [转载] sklearn FutureWarning: numpy not_equal will not check..., The comparison did not return the sam
  4. [转载] python的 for、while循环、嵌套循环
  5. spring cloud config-配置中心
  6. 通过docker-composer启动容器nginx,并完成spring.boot的web站点端口转发
  7. struts2与spring集成时,关于class属性及成员bean自动注入的问题
  8. [1.1]用WebService返回歌曲的曲目信息.借鉴[星集工作室 张麟 Dephi版]
  9. Python---copy()、deepcopy()与赋值的区别
  10. 【C++笔记】函数的用法:函数的默认参数、占位参数、函数重载