我正在尝试创建自定义时间选择器。但遇到的问题是当我旋转屏幕时。此外,如果我按下主页按钮离开应用程序,当我带着相同的错误回来时它会崩溃。
public class MyTimePicker extends RelativeLayout {
private NumberPicker hour;
private NumberPicker minute;
private NumberPicker am;
private int interval = 5;
public MyTimePicker(Context context) {
super(context);
init();}
public MyTimePicker(Context context, AttributeSet attrs) {
super(context, attrs);
init();}
public MyTimePicker(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();}
private void init() {
LayoutInflater inflater = LayoutInflater.from(getContext());
if (inflater != null) {
String[] ams = new String[2];
ams[0]="AM";
ams[1]="PM";
root = inflater.inflate(R.layout.my_time_picker, this, true);
hour = (NumberPicker) root.findViewById(R.id.hour);
minute = (NumberPicker) root.findViewById(R.id.minute);
am = (NumberPicker) root.findViewById(R.id.am); am.setDisplayedValues(ams);
am.setWrapSelectorWheel(true);
am.setMinValue(0);
am.setMaxValue(1);
String[] hours = new String[24];
for (int i = 0; i < 24; i++) {
hours[i]= "" + (i < 12 ? i + 1 : i - 11);
}
String[] mins = new String[60 / interval];
NumberFormat formatter = new DecimalFormat("00");
for (int i = 0; i < mins.length; i++) {
mins[i] = formatter.format(i * interval);
}
hour.setDisplayedValues(hours);//This is what causes the error
hour.setWrapSelectorWheel(true);
hour.setMinValue(0);
hour.setMaxValue(hours.length - 1);
minute.setDisplayedValues(mins);//This is what causes the error
minute.setWrapSelectorWheel(true);
minute.setMinValue(0);
minute.setMaxValue(mins.length - 1);
}
}
}
这是错误即将到来
06-24 15:15:50.509 2006-2006/com.E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.mye.appo, PID: 2006
java.lang.IndexOutOfBoundsException: setSpan (2 ... 2) ends beyond length 0
at android.text.SpannableStringBuilder.checkRange(SpannableStringBuilder.java:1018)
at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:611)
at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:607)
at android.text.Selection.setSelection(Selection.java:76)
at android.widget.EditText.setSelection(EditText.java:92)
at android.widget.NumberPicker$SetSelectionCommand.run(NumberPicker.java:2189)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
我发现如果只在if(this.isVisible())
时设置片段或活动的显示值,我可以防止此崩溃从我发现这似乎是一个生命周期问题
答案 0 :(得分:2)
由于错误 - 在使用NumberPicker对象之前尝试设置:
NumberPicker.setSaveFromParentEnabled(false);
NumberPicker.setSaveEnabled(false);
我开了一个这个&amp;的问题。数字选择器的其他错误: