In this tutorial, we’ll be discussing and implementing Spinners in our Android Application using Kotlin. Android Spinner is used to create a drop-down list on the screen.

在本教程中,我们将使用Kotlin在Android应用程序中讨论和实现Spinners。 Android Spinner用于在屏幕上创建一个下拉列表。

What will you learn?你会学什么?

  • Creating Spinners through XML and Programmatically通过XML和编程方式创建微调器
  • Setting a prompt on the Spinner.在微调器上设置提示。
  • Creating a custom layout for the Spinner.为微调框创建自定义布局。
  • Handling Click Listeners and Display a Toast message.处理单击侦听器并显示Toast消息 。
  • Preventing the Click Listener from being fired automatically for the first time.防止首次自动触发Click Listener。

什么是Android Spinner? (What is Android Spinner?)

Spinners are like a drop-down menu that contains a list of items to select from. Once a value is selected the Spinner returns to its default state with that selected value.

微调框就像一个下拉菜单,其中包含要选择的项目列表。 选择一个值后,微调框将使用所选值返回其默认状态。

After Android 3.0, it’s not possible to display a prompt in a Spinner as the default state in the Spinner. Instead, the first item is displayed.

在Android 3.0之后,无法在Spinner中显示提示作为Spinner中的默认状态。 而是显示第一项。

Data inside a spinner is loaded with an Adapter.

微调器内部的数据已加载有适配器。

Take the following scenario:

请采取以下情况:

Imagine you need to charge your phone. For that, you must connect your phone charger to the electricity board using a pin (adapter). Then the adapter provides your phone with electricity. In Android, the Spinner is like your phone which is loaded with data using an Adapter. The adapter sets the data as well as the layout for the items to be loaded in the Spinner.

假设您需要为手机充电。 为此,必须使用引脚(适配器)将手机充电器连接到配电板上。 然后,适配器为您的手机供电。 在Android中,Spinner就像您的手机一样,它使用Adapter加载了数据。 适配器设置数据以及要在微调器中加载的项目的布局。

微调器回调事件 (Spinner Callback Events)

AdapterView.onItemSelectedListener interface is used to trigger the Spinner click event callbacks.

AdapterView.onItemSelectedListener接口用于触发Spinner点击事件回调。

It consists of two methods:

它包含两种方法:

  • onItemSelectedonItemSelected
  • onNothingSelectedonNothingSelected

In the following section, we’ll create a new Android Studio Project and implement Spinners in our Application. We’ll customize the layouts and learn how to handle different scenarios.

在下一节中,我们将创建一个新的Android Studio项目并在应用程序中实现Spinners。 我们将自定义布局,并学习如何处理不同的场景。

Android Spinner Kotlin项目 (Android Spinner Kotlin Project)

1. XML布局代码 (1. XML Layout Code)

The code for the activity_main.xml layout file is given below.

下面给出了activity_main.xml布局文件的代码。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"android:id="@+id/linearLayout"android:gravity="center"tools:context=".MainActivity"><Spinnerandroid:id="@+id/mySpinner"android:layout_width="match_parent"android:spinnerMode="dialog"android:layout_height="wrap_content" /></LinearLayout>

It hosts a single Spinner at the moment android:spinnerMode can be either dialog or dropdown.

android:spinnerMode可以是dialogdropdown它会托管一个Spinner。

spinnerMode value.spinnerMode值。

2.微调器XML代码 (2. Spinner XML Code)

The code for spinner_right_aligned.xml is given below.

下面给出了spinner_right_aligned.xml的代码。

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"android:id="@+id/textView"android:layout_width="match_parent"android:layout_height="wrap_content"android:gravity="end"android:padding="15dp"android:textAlignment="gravity"android:textColor="@color/colorPrimary"android:textSize="16sp"/>

3. MainActivity Kotlin代码 (3. MainActivity Kotlin Code)

The code for the MainActivity.kt class is given below.

MainActivity.kt类的代码如下。

package net.androidly.androidspinnerkotlinimport android.content.Context
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.widget.*
import kotlinx.android.synthetic.main.activity_main.*class MainActivity : AppCompatActivity(), AdapterView.OnItemSelectedListener {var languages = arrayOf("Java", "PHP", "Kotlin", "Javascript", "Python", "Swift")val NEW_SPINNER_ID = 1override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)var aa = ArrayAdapter(this, android.R.layout.simple_spinner_item, languages)aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)with(mySpinner){adapter = aasetSelection(0, false)onItemSelectedListener = this@MainActivityprompt = "Select your favourite language"gravity = Gravity.CENTER}val spinner = Spinner(this)spinner.id = NEW_SPINNER_IDval ll = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)ll.setMargins(10, 40, 10, 10)linearLayout.addView(spinner)aa = ArrayAdapter(this, R.layout.spinner_right_aligned, languages)aa.setDropDownViewResource(R.layout.spinner_right_aligned)with(spinner){adapter = aasetSelection(0, false)onItemSelectedListener = this@MainActivitylayoutParams = llprompt = "Select your favourite language"setPopupBackgroundResource(R.color.material_grey_600)}}override fun onNothingSelected(parent: AdapterView<*>?) {showToast(message = "Nothing selected")}override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {when (view?.id) {1 -> showToast(message = "Spinner 2 Position:${position} and language: ${languages[position]}")else -> {showToast(message = "Spinner 1 Position:${position} and language: ${languages[position]}")}}}private fun showToast(context: Context = applicationContext, message: String, duration: Int = Toast.LENGTH_LONG) {Toast.makeText(context, message, duration).show()}
}

Important Points:

重要事项

  • Thanks to Kotlin Android extensions, the XML Spinner widget is automatically available in our Kotlin Activity class.感谢Kotlin Android扩展,XML Spinner小部件可在我们的Kotlin Activity类中自动提供。
  • We’ve created an arrayOf strings that consist of programming languages. These are filled in the adapter using the ArrayAdapter.我们创建了一个由编程语言组成的arrayOf字符串。 这些使用ArrayAdapter填充到适配器中。
  • The setDropDownViewResource is used to set the layout for the selected state and the spinner list rows.setDropDownViewResource用于设置选定状态和微调setDropDownViewResource列表行的布局。
  • The android.R.layout.simple_spinner_item is used to set the default android SDK layout. By default, the TextView is left aligned in this type of layout.android.R.layout.simple_spinner_item用于设置默认的android SDK布局。 默认情况下, TextView在这种布局中保持对齐。

We’ve created a second Spinner programmatically that loads the layouts from the spinner_right_aligned.xml file.

我们已经以编程方式创建了第二个Spinner,它从spinner_right_aligned.xml文件中加载布局。

setSelection(0, false) is used to prevent the Spinner’s OnItemSelected methods from firing when the Activity is created.setSelection(0, false)用于防止在创建Activity时触发Spinner的OnItemSelected方法。

How does it work?
The setSelection() method tells the Activity that the first spinner item was already selected. We must place this statement before onItemSelectedListener = this.

它是如何工作的?
setSelection()方法告诉Activity已经选择了第一个微调器项目。 我们必须将此语句onItemSelectedListener = this之前。

The setPopupBackgroundResource is used to set the background color on the dropdown list.

setPopupBackgroundResource用于在下拉列表上设置背景颜色。

Inside the onItemSelected function, we use the when statement to trigger a Toast for the respective Spinner item.

onItemSelected函数内部,我们使用when语句为相应的Spinner项触发Toast。

Thanks to Kotlin and functions with default values, we’ve reduced the verbose call to the Toast.

感谢Kotlin和具有默认值的函数,我们减少了对Toast的冗长调用。

4. Spinner Kotlin应用程序输出 (4. Spinner Kotlin App Output)

The following is the output when the above application was run on an emulator.

以下是在模拟器上运行上述应用程序时的输出。

You can download the source code of the above project from the link below.
AndroidSpinnerKotlin

您可以从下面的链接下载上述项目的源代码。
AndroidSpinnerKotlin

翻译自: https://www.journaldev.com/214/android-spinner-using-kotlin

使用Kotlin的Android Spinner相关推荐

  1. 用Kotlin写Android Gradle脚本

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

  2. Kotlin for Android

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

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

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

  4. Android Spinner值不显示,选择列表正常

    Android Spinner值不显示,选择列表正常 本Markdown编辑器使用[StackEdit][6]修改而来,用它写博客,将会带来全新的体验哦: 1.项目开发过程中,只有小米的手机出现这个问 ...

  5. 用Kotlin开发android平台语音识别语义理解应用

    用Kotlin开发android平台语音识别,语义理解应用(olamisdk) 转载请注明CSDN博文地址:http://blog.csdn.net/ls0609/article/details/75 ...

  6. Kotlin on Android 开发环境介绍

    Kotlin 被 Google 采纳为 Android 开发一级编程语言,到现在也一年多了,我们团队从去年 10 月份开始部分项目尝试用 Kotlin 开发,到现在决定推广到全部项目,因为一旦用上 K ...

  7. 用Kotlin开发android平台语音识别,语义理解应用(olamisdk)

    本文使用Kotlin开发Android平台的一个语音识别方面的应用,用的是欧拉密开放平台olamisdk. 1.Kotlin简介 Kotlin是由JetBrains创建的基于JVM的编程语言,Inte ...

  8. Java vs Kotlin,Android开发人员应该选择哪种语言?

    自 Google 于 2017 年宣布 Kotlin 成为 Google IO 的 Android 开发官方语言以来,想要成为Android开发人员的程序员正陷入两难境地. 在讨论这个问题前,我首先要 ...

  9. 从零开始学android编程_小白也能学得会!谷歌推出免费的Kotlin和Android开发课程...

    程序员书库(ID:CodingBook) 猿妹编译 链接:https://android-developers.googleblog.com/2020/07/learn-android-and-kot ...

最新文章

  1. Android内存优化(三)避免可控的内存泄漏
  2. springmvc的工作原理_SpringMVC工作原理
  3. python 为什么没有重载_python是否支持重载
  4. Windows XP SP2疑难速解50问
  5. [JavaME]解决来电问题(Incoming Call)
  6. Microsoft SQL server 2008 安装未取得权限操作
  7. tfrecord数据报错 InvalidArgumentError: Feature: feature (data type: string) is required but could not
  8. 甩开镣铐的精神舞蹈:推荐长篇小说《炼狱之花》
  9. 【LightOJ - 1104】Birthday Paradox(概率,思维)
  10. mysql for vs2013_mysql vs2013
  11. 文件服务器 ip,共享文件服务器的ip地址
  12. Linux SOCKET编程详解
  13. Saltstack 安装应用笔记一
  14. Node.js内存泄漏分析
  15. 计算机毕业设计springboot+vue基本微信小程序的考试系统
  16. linux装pl2303驱动下载,Linux下安装USB转串口驱动(PL2303)
  17. twitter授权登录 php,PHP版实现Twitter第三方登录的成功案例
  18. 宅家羊毛党是怎么做到月入上万的
  19. 推荐系统视频行业揭秘,“抖音快手”现象级产品背后的推荐逻辑
  20. React.js -学习总结1

热门文章

  1. [AlwaysOn Availability Groups]健康模型 Part 1——概述
  2. Unable to find the requested .Net Framework Data Provider
  3. 珍惜生命 远离中国足球
  4. [转载] Python算法
  5. Quartus 与modelSim联合仿真常见错误以及系统任务$readmemb和$readmemh解释
  6. PLL与PHY的连接:通道绑定或者不绑定
  7. python day1 5:23
  8. Monkey之环境搭建
  9. 拼多多服务端实习生笔试-滑动窗口2018/4/3
  10. springcloud-provider-consumer-register