android NumberPicker 数组越界的坑

被这个问题耽误了一个多小时。。。

直接上解决方案,参考红色部分。

private void initViews() {
        wheel = (NumberPicker) findViewById(R.id.info_wheel_province);
        wheelCity = (NumberPicker) findViewById(R.id.info_wheel_city);
        wheelCity.setWrapSelectorWheel(false);

        //读取地址信息json
        final List<CityBean> cityBeans = ResUtils.initCityList(this);
        final String[] pros = new String[cityBeans.size()];

        for (int i = 0; i < pros.length; i++) {
            pros[i] = cityBeans.get(i).getProvince();
        }

//        wheel.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
//        wheelCity.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
        wheel.setMaxValue(pros.length - 1);
        wheel.setMinValue(0);
        wheel.setWrapSelectorWheel(false);
        wheel.setDisplayedValues(pros);
        wheel.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {

            @Override
            public void onValueChange(NumberPicker picker, int oldVal, final int newVal) {
                String citys = cityBeans.get(newVal).getCitys();
                final String[] split = citys.split(",");
                wheelCity.setMinValue(0);
                wheelCity.setValue(0);
                if (split.length - 1 > wheelCity.getMaxValue()) {
                    wheelCity.setDisplayedValues(split);
                    wheelCity.setMaxValue(split.length - 1);
                } else {
                    wheelCity.setMaxValue(split.length - 1);
                    wheelCity.setDisplayedValues(split);
                }
                wheelCity.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {

                    @Override
                    public void onValueChange(NumberPicker picker2, int oldVal2, int newVal2) {
                        Toast.makeText(InfoActivity.this, pros[newVal] + " " + split[newVal2], Toast.LENGTH_LONG).show();
                    }
                });
            }
        });
    }

有兴趣的可以研究一下源码找下原因。

posted @ 2015-08-02 15:57  带狗狗带  Views(915)  Comments(0Edit  收藏  举报