1

Whenever I call setSelection for my spinners, I OnItemSelectedListener is called. In some specific cases it breaks my app. In other words, this has to stop happening. The problem is that OnItemSelectedListener seems to be called through the message queue. A trivial solution doesn't work:

private void setCurrentItem(int id) 
{
    m_bControlChanging = true;
    sp.setSelection(adapter.ordById(id));
    m_bControlChanging = false;
}

private class SpinnerItemSelected implements OnItemSelectedListener {

    public void onItemSelected(AdapterView<?> view, View textView, int ord, long arg3) {

        if (m_bControlChanging)
            return;

        // Do work...
    }

    public void onNothingSelected(AdapterView<?> arg0) {}
}

How can I solve the problem?

4

2 回答 2

2

您的解决方案将不起作用,因为标志在您测试之前被重置。您需要一个握手解决方案,即:

private void setCurrentItemInCbCS(int ct, int id) 
{
    m_bControlChanging = true;
    sp.setSelection(adapter.ordById(id));
}

private class SpinnerItemSelected implements OnItemSelectedListener {

    public void onItemSelected(AdapterView<?> view, View textView, int ord, long arg3) {
        boolean b = m_bControlChanging;
        m_bControlChanging = false;

        if (b)
            return;

        // Do work...
    }

    public void onNothingSelected(AdapterView<?> arg0) {}
}
于 2013-09-11T14:37:00.163 回答
2

我同意 Clad Clad 的观点,但如果您想忽略回调,您可以“记住”最后一次手动设置的选择并在回调中忽略它。

例如:

private int lastManuallySetSelection = -1;

private void setCurrentItemInCbCS(int ct, int id) 
{
    sp.setSelection(lastManuallySetSelection = adapter.ordById(id));
}

private class SpinnerItemSelected implements OnItemSelectedListener {

public void onItemSelected(AdapterView<?> view, View textView, int ord, long arg3) {

    if (ord == lastManuallySetSelection) {
        lastManuallySetSelection = -1;
        return;
    }

    // Do work...
}

public void onNothingSelected(AdapterView<?> arg0) {}
}
于 2013-09-11T14:38:33.530 回答