Android 数字选择器键盘类型

标签 android

我有一个 EditText,单击它会创建一个包含数字选择器的 AlertDialog。我想为用户提供滚动数字选择器以及通过键盘输入值的选项。但我不知道如何为 NumberPicker 设置键盘类型,目前在单击数字选择器的值时会显示完整的键盘。

我知道 EditText 可以执行 editText.setInputType,但是对于 NumberPicker 呢?


这是我的对话框 xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:holo="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="horizontal" >

<NumberPicker
    android:id="@+id/numberPicker1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"/>
</LinearLayout>

我不想设置编辑文本的输入类型。我想设置数字选择器的输入类型。单击编辑文本时,会创建一个对话框,其中包含一个数字选择器。它是我要设置输入类型的那个数字选择器。

最佳答案

默认情况下,NumberPicker 现在使用 inputType="number"除非您设置了 displayedValues,这会恢复键盘到完整模式,因为显示的值是 String[]

在某些用例中,您可能希望覆盖此行为,例如如果您的值是非连续数字(0、5、10 等)或 float (1.0、1.5 等)。这是基于 this question 的解决方案:

// Java
private void setInput(ViewGroup vg) {
    for(int i = 0; i < vg.getChildCount(); i++) {
        View child = vg.getChildAt(i);
        if(child instanceof ViewGroup) {
            // Recurse
            setInput((ViewGroup) child);
        } else if(child instanceof EditText) {
            // Force InputType
            ((EditText) child).setInputType(InputType.TYPE_CLASS_NUMBER);
        }
    }
}

……或者……

// Kotlin
private fun setInput(vg: ViewGroup) {
    (0..vg.childCount).map { vg.getChildAt(it) }.forEach {
        when (it) {
            is ViewGroup -> setInput(it) // recurse
            is EditText -> it.inputType = InputType.TYPE_CLASS_NUMBER
        }
    }
}

关于Android 数字选择器键盘类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16793414/

相关文章:

android - 更改 RecyclerView 项目的项目背景

java - 带时区的简单日期格式

android - 在 Linux 操作系统 (Ubuntu) : Android Facebook SDK 中生成发布 key 哈希

android - 无论屏幕大小如何,始终从 mdpi 文件夹中读取可绘制对象

Android SecurityException CALL_PHONE 尽管我在 list 文件中声明了它

android - 是否可以在 Android 上使 mapview 在没有 api key 的情况下工作?

java - 更新 List<Object> 中的对象仅影响特定字段。 (合并)

android - 有什么方法可以在您的网络上发现 Android 设备?

android - TextView 中的自动链接 Action 跟踪 onClickListener

javascript - Phonegap Cordova - 如何删除默认的启动屏幕?