使用Kotlin的Android Spinner

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

你将学到什么?

  • 通过 XML 和编程方式创建 Spinners
  • 在 Spinner 上设置提示。
  • 为 Spinner 创建自定义布局。
  • 处理点击事件并显示 Toast 消息
  • 防止第一次自动触发点击事件监听器。

什么是 Android Spinner?

旋转器就像一个下拉菜单,其中包含要从中选择的项目列表。选择值后,旋转器将返回到其默认状态,并显示所选值。在Android 3.0之后,不可能在旋转器中显示提示作为默认状态。相反,将显示第一项。旋转器内的数据是使用适配器加载的。想象一下以下情景:假设您需要给手机充电。为此,您必须使用引脚(适配器)将手机充电器连接到电力板上。然后适配器为您的手机提供电力。在Android中,旋转器就像您的手机,使用适配器加载数据。适配器设置要在旋转器中加载的项目的数据以及布局。

旋转器回调事件

AdapterView.onItemSelectedListener接口用于触发旋转器单击事件回调。它包含两个方法:

  • onItemSelected
  • onNothingSelected

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

Android旋转器Kotlin项目

1. XML布局代码

下面是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">

    <Spinner
        android:id="@+id/mySpinner"
        android:layout_width="match_parent"
        android:spinnerMode="dialog"
        android:layout_height="wrap_content" />

</LinearLayout>

目前它只包含一个下拉框,android:spinnerMode属性可以是dialogdropdown

要显示提示,应将spinnerMode的值设置为dialog。

2. 下拉框XML代码

下面是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 代码

下面是MainActivity.kt类的代码。

package net.androidly.androidspinnerkotlin

import 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 = 1

    override 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 = aa
            setSelection(0, false)
            onItemSelectedListener = this@MainActivity
            prompt = "Select your favourite language"
            gravity = Gravity.CENTER

        }

        val spinner = Spinner(this)
        spinner.id = NEW_SPINNER_ID

        val 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 = aa
            setSelection(0, false)
            onItemSelectedListener = this@MainActivity
            layoutParams = ll
            prompt = "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()
    }
}

重要提示:

  • 由于Kotlin Android扩展,XML下拉框小部件在我们的Kotlin Activity类中自动可用。
  • 我们创建了一个由编程语言组成的字符串数组。这些字符串被填充到适配器中使用ArrayAdapter。
  • setDropDownViewResource用于设置所选状态的布局和下拉框列表行的布局。
  • android.R.layout.simple_spinner_item 用于设置默认的 Android SDK 布局。默认情况下,在这种类型的布局中,TextView 左对齐。

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

使用 setSelection(0, false) 可以防止 Spinner 在创建 Activity 时触发 OnItemSelected 方法。

它是如何工作的? setSelection() 方法告诉 Activity 第一个 Spinner 项已经被选择。我们必须在 onItemSelectedListener = this 之前放置这个语句。setPopupBackgroundResource 用于设置下拉列表的背景颜色。在 onItemSelected 函数内部,我们使用 when 语句触发相应 Spinner 项的 Toast。由于 Kotlin 和带有默认值的函数,我们减少了对 Toast 的冗长调用。

4. Spinner Kotlin 应用输出

当上述应用在模拟器上运行时,以下是输出结果。您可以从下面的链接下载上述项目的源代码。AndroidSpinnerKotlin

Source:
https://www.digitalocean.com/community/tutorials/android-spinner-using-kotlin