加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – NumberPicker不能与键盘一起使用

发布时间:2020-12-15 02:06:29 所属栏目:Java 来源:网络整理
导读:在activity_main.xml中: NumberPicker android:id="@+id/numberPicker1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/textView2" android:layout_centerHorizontal="true" android:layout_margi
在activity_main.xml中:

<NumberPicker
        android:id="@+id/numberPicker1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView2"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="30dp" />

在oncreate里面的MainActivity.java中:

NumberPicker numberPicker1 = (NumberPicker) findViewById(R.id.numberPicker1);
numberPicker1.setMinValue(1);
numberPicker1.setMaxValue(20);

当我用键盘编辑值时,我以编程方式获得的值不会改变,但是如果我按下那么 – 它可以工作.

如何让它工作而不必按和 – ?

编辑:

我用MelihAlt?nta?的代码创建了一个新项目,它显示了一个全新的数字选择器! (用手指滑动但不能输入文字的那个).然后我比较了我的真实项目,我看到了android:theme =“@ android:style / Theme.NoTitleBar”.我在新项目中添加了它,然后numberpicker成为我习惯的那个.

解决方法

NumberPicker不是为该交互而设计的.当您使用键盘更改值时,您正在从NumberPicker直接更改窗口小部件,并且窗口小部件本身不会看到此更改,因此这就是您最终存储最后一个值的原因.要解决这个问题,你需要一些hacky代码,这不是真正推荐的,因为你需要访问底层的EditText(假设手机制造商并没有改变这一点):

private EditText findInput(ViewGroup np) {
    int count = np.getChildCount();
    for (int i = 0; i < count; i++) {
        final View child = np.getChildAt(i);
        if (child instanceof ViewGroup) {
            findInput((ViewGroup) child);
        } else if (child instanceof EditText) {
            return (EditText) child;
        }
    }
    return null;
}

然后你将使用这段代码在找到的EditText上设置TextWatcher,看看它何时被手动修改(并让NumberPicker知道这个变化):

EditText input = findInput(np);    
TextWatcher tw = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s,int start,int before,int count) {}

        @Override
        public void beforeTextChanged(CharSequence s,int count,int after) {}

        @Override
        public void afterTextChanged(Editable s) {
                if (s.toString().length() != 0) {
                    Integer value = Integer.parseInt(s.toString());
                    if (value >= np.getMinValue()) {
                        np.setValue(value);
                    }
                }
        }
    };
input.addTextChangedListener(tw);

另一种选择是自己实现NumberPicker小部件并插入您目标的功能.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读