我正在使用自定义数字选择器来显示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值设置为数字选择器。请告诉我如何实现这一点。提前感谢..
答案 0 :(得分: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]
)