微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

奇怪的Android Spinner行为

这是填充我的微调器的代码.

编码:

String[] rcs = new String[review_cycles.length];
for (int i = 0; i < review_cycles.length; i++)
    rcs[i] = review_cycles[i].ReviewCycleName;
ArrayAdapter<String> rc_spinnerAdapter = new ArrayAdapter<String>(
        ActivityManagementReview.this,
        R.layout.simple_spinner_item, 
        rcs);
sp_review_cycle.setAdapter(rc_spinnerAdapter);
sp_review_cycle.setonItemSelectedListener(new OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
        DtomrReviewCycLeversion selected_review_cycle_version = review_cycles[position];
        if (selected_review_cycle_version != latest_review_cycle_version) {
            latest_review_cycle_version = selected_review_cycle_version;
            int mr_version_id = latest_review_cycle_version.MrdVersionId;
            _URL_version = _url_base + "MrVersion/" + Integer.toString(mr_version_id);
            new GetMrVersionInfoAsyncTask().execute();
        }
    }

    @Override
    public void onnothingSelected(AdapterView<?> parentView) {
        return;
    }
});

当我从微调器中选择一个值时,代码执行两次.一旦我做了选择,然后立即执行,列表中的第一项再次执行,让我回到我开始的地方.

我怎样才能防止这种情况发生?

谢谢.

解决方法:

When I select a value from the spinner, the code is executed twice.

正如我在评论中提醒你的那样,Spinners在加载认值时会调用onItemSelected().当您了解它时,此功能非常有用,但由于它不是普通开发人员所期望的,因此也存在问题.

用户重新选择当前值时,Spinner也会调用onItemSelected()…当我想避免这两个误报时,我使用这样的东西:

spinner.setonItemSelectedListener(new OnItemSelectedListener() {
    int prevIoUs = -1;
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        if(prevIoUs != position && prevIoUs < -1) {
            Log.v("Example", "Selected: " + position);
            // Do something
        }
        prevIoUs = position;
    }

    @Override
    public void onnothingSelected(AdapterView<?> parent) {}
});

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐