如何使用两个NumberPickers创建更好的TimePicker(小时值增量/减量为分钟值超过59/0)?

时间:2016-06-02 17:54:02

标签: android numberpicker android-timepicker

在创建一个作为倒数计时器的应用程序时,我需要创建一个对话框来设置倒计时的时间。当我尝试使用TimePicker时,我意识到我无法以我想要的方式使用它,也就是说,选择上限为24小时的小时数。此外,我无法设置秒数。

所以,我必须使用2个NumberPickers实现我自己的TimePicker。 (我还没有包括秒NumberPicker)

我想添加一个由TimePicker给出的微小功能,如果我将分钟选择器滚过值59到值00,它会将小时值增加1(如果我是的话,同样减少它)从00到59)。

示例:

Example

我使用以下代码来实现我的目的,但仍然存在一个小问题。

Java代码:

final NumberPicker hr_np = (NumberPicker) d.findViewById(R.id.hr_timepicker);
final NumberPicker min_np = (NumberPicker) d.findViewById(R.id.min_timepicker);     
min_np.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
        @Override
        public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
            if(newVal==0 && oldVal==59 && hr_np.getValue()<10)
                hr_np.setValue(hr_np.getValue()+1);
            else if(newVal==59 && oldVal==0 && hr_np.getValue()>0)
                hr_np.setValue(hr_np.getValue()-1);
        }
    });

XML布局:

<LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">



    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center">
        <NumberPicker
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/hr_timepicker" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=":"
            android:textSize="40sp"
            android:textIsSelectable="true" />
        <NumberPicker
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/min_timepicker" />
    </LinearLayout>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Set"
        android:id="@+id/b1"
        android:layout_marginTop="40dp" />

</LinearLayout>

问题是,当我单击NumberPicker值并直接输入新值时,上述逻辑仍然存在。比如说,当前时间是03:59,我点击分钟标签并输入00,时间变为04:00。这也发生在正常的TimePicker中。

有没有办法解决这个问题?

1 个答案:

答案 0 :(得分:0)

为什么不简单地使用timepicker

<TimePicker
      android:id="@+id/timePicker1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content" />