【问题标题】:set number picker am pm value dynamically动态设置数字选择器 am pm 值
【发布时间】:2017-11-08 11:20:36
【问题描述】:

我正在开发用于显示 AM 和 PM 值的自定义数字选择器。请检查下面的数字选择器代码。

<com.naushad.kenocustomer.util.NumberPicker
                    android:id="@+id/np_ampm"
                    android:layout_width="wrap_content"
                    android:layout_height="130dp"
                    android:layout_marginTop="10dp"
                    android:layout_marginBottom="10dp"
                    android:layout_centerHorizontal="true"/>

XML 代码如下所示,下面是 java 代码。

    final String ampm[] = {"AM", "PM"};
            datetimeBinding.npAmpm.setFormatter(R.string.number_picker_formatter);

            datetimeBinding.npAmpm.setSelectedTextColor(Color.parseColor("#09bcf2"));
            datetimeBinding.npAmpm.setTextColor(Color.parseColor("#babdc2"));
            datetimeBinding.npAmpm.setDefaultSelectedTextSize(20);
            datetimeBinding.npAmpm.setTextSize(getResources().getDimension(R.dimen.fifteen));

            datetimeBinding.npAmpm.setMinValue(1);
            datetimeBinding.npAmpm.setMaxValue(ampm.length);
            datetimeBinding.npAmpm.setDisplayedValues(ampm);
int isAM = c.get(Calendar.AM_PM);
        int myValue = Arrays.asList(ampm).indexOf(String.valueOf(isAM));
        if(isAM == 0)
            datetimeBinding.npAmpm.setValue(Integer.parseInt(ampm[1].toString()));
        else
            datetimeBinding.npAmpm.setValue(Integer.parseInt(ampm[1].toString()));

现在我将根据当前时间动态设置数字选择器值。但我已经按照以下方式编写代码并获得 数字格式异常。

我想根据当前时间将 am pm 值设置为数字选择器。请建议我如何实现这一点。提前谢谢..

【问题讨论】:

    标签: android numberpicker android-number-picker


    【解决方案1】:

    我猜你在这里的某个地方遇到了错误?

     if(isAM == 0)
            datetimeBinding.npAmpm.setValue(Integer.parseInt(ampm[1].toString()));
        else
            datetimeBinding.npAmpm.setValue(Integer.parseInt(ampm[1].toString()));
    

    这似乎是合理的,因为ampm[1] 包含字符串“AM”并且在

    Integer.parseInt(ampm[1].toString()) 
    

    您尝试将其解析为整数,但“AM”不是数字而是字符串。因此一个

    java.lang.NumberFormatException: For input string: "PM"
    

    例外是完全合理的。如果要将其显示为字符串,请去掉 Integer.parseInt(...)。我不知道你的datetimeBinding.npAmpm到底是什么,但如果是普通标签,就这样设置?

    datetimeBinding.npAmpm.setValue(ampm[1]);
    

    (另外:在if(isAM == 0) 的两种情况下,您都使用ampm[1],我猜其中之一应该是ampm[0]

    【讨论】:

    • 是的,你是对的,我在同一行得到了例外。
    • 是的,正如我解释的那样。您不能将“AM”转换为数字,因为“AM”不是数字。
    • 但是如何动态更改 AM PM 值??
    • 我向您解释了您的异常来自何处。如果你想动态改变它,你必须在视图中添加一个监听器并改变这个监听器中的值。
    • 但根据您的解释,它在 setValue() 中不接受任何字符串值。它只允许 int 值作为参数..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-25
    相关资源
    最近更新 更多