安卓系统中是否有用于输入整数的视图?

23

我正在寻找类似于日期选择器对话框中单个部分的东西。一个视图,允许您输入整数(仅限整数),并且可以限制这些数字(例如在1和10之间),您可以使用键盘或视图本身中的箭头。它存在吗?

这是为对话框而设计的。一个现成的对话框可请求整数也会有所帮助。

5个回答

23

NumberPicker 控件可能是你想要的。不幸的是,它位于 com.android.internal.Widget.NumberPicker 中,我们无法通过正常方式访问它。

有两种使用方法:

  1. 从 Android 源代码复制代码
  2. 使用反射访问该小部件

这是在布局中使用它的 XML:

<com.android.internal.widget.NumberPicker
    android:id="@+id/picker"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

这里是设置NumberPicker设置的反射代码(我没有测试过):

Object o = findViewById(R.id.picker);
Class c = o.getClass();
try 
{
    Method m = c.getMethod("setRange", int.class, int.class);
    m.invoke(o, 0, 9);
} 
catch (Exception e) 
{
    Log.e("", e.getMessage());
}

由于这是一个内部小部件而不是SDK中的一部分,如果使用反射可能会破坏未来的兼容性。最安全的方法是从源代码自己开发。

此信息的原始来源在此 Google Group 中共享。


7
NumberPicker内部小部件已从Android源代码中提取并打包供您使用,您可以在此处找到它。非常好用!
编辑:原链接已失效,您可以在此处找到该小部件的一个副本。

@AlanMoore 看起来是这样的... 这是我在我的开源应用程序中使用的源代码:http://code.google.com/p/tippytipper/source/browse/trunk/Tippy%20Tipper/src/net/mandaria/tippytipper/widgets/NumberPicker.java - Bryan Denny
第二个链接似乎也无法访问。 - Forrest Bice
@ForrestBice 我已经将源代码重新排列,使用了一个Android库项目。该文件的新位置在这里:https://code.google.com/p/tippytipper/source/browse/trunk/Tippy%20Tipper%20Library/src/net/mandaria/tippytipperlibrary/widgets/NumberPicker.java - Bryan Denny

4

0

您可以简单地使用 EditText 并将 inputType 定义为 number。例如:

        <EditText
            android:id="@+id/etNumberInput"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="8dp"
            android:inputType="number" />

如果要将最大值限制为10,可以通过编程实现:

        final EditText et = findViewById(R.id.etNumberInput);

        et.addTextChangedListener(new TextWatcher() {
          
            public void afterTextChanged(Editable s) {}
            
            public void beforeTextChanged(CharSequence s, int start,
                                          int count, int after) {}
            
            public void onTextChanged(CharSequence s, int start,
                                      int before, int count) {
                if (Integer.parseInt(et.getText().toString()) > 10) {
                    et.setError("***Your error here***");
                    // your logic here; to limit the user from inputting
                    // a value greater than specified limit
                }
            }
        });

这应该能够达到你的目标。


0
你可以使用EditText的android:inputType="number"属性。
<EditText android:layout_height="wrap_content" android:id="@+id/editText1" android:inputType="number" android:layout_width="wrap_content"></EditText>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接