Spinner OnclickListener事件执行两次,如何处理这两个事件

时间:2011-08-22 11:03:21

标签: android spinner

Spinner OnclickListener事件执行两次 -

  • Spinner初始化
  • 手动选择用户

其中侦听器的实现如下:

spinner.setOnItemSelectedListener(new OnItemSelectedListener() {           
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

            }

            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

问题定义

当用户从微调器中选择任何项目时,我想将用户选择的文本保存到数据存储中,我能够执行此操作。但我的另一项任务是将以前选择的项目(从数据存储中访问)显示为微调器中的选定项目,但每次调用微调器的活动时,微调器都会将第一项显示为默认选定项目,并且在数据存储中也会更改以前的项目项目为默认值。

如何区分'Spinner初始化'和'手动选择用户'事件?

2 个答案:

答案 0 :(得分:7)

您必须逻辑地处理这两个事件。由于这些引用(Android Spinner selectionproblem on spinner)表示您必须使用标志变量来处理此问题,因此我将使用代码示例。

希望这可以帮助您清除逻辑。

public class TestActivity extends Activity {  

    //Checks report spinner selection is default or user selected item
    private boolean isDefaultSelection;
    //Spinner setup
    Spinner spinner;

   @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.your_layout);

        // Set true at onCreate
        isDefaultSelection = true;

         spinner = (Spinner) findViewById(R.id.id_of_spinner);      
        ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String> (this, R.layout.drop_down_custom_row, data);
        //Implement custom view for drop down of spinner
        //spinnerAdapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(spinnerAdapter);
        spinner.setOnItemSelectedListener(new OnItemSelectedListener() {          
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                if(isDefaultSelection) { //If spinner initializes
                    spinner.setSelection("Set_here_id_of_data_item_from_storage_which_was_previously_stored");
                    isDefaultSelection = false;
                } else { //If user manually select item
                    int itemPosition = spinner.getSelectedItemPosition();
                    //Write here code to store selection (itemPosition) of user into data storage
                }
            }

            public void onNothingSelected(AdapterView<?> parent) {
                //User selected same item. Nothing to do.
            }
        });

    }

}

希望它能清除你的怀疑。

答案 1 :(得分:-1)

您可以在将项目添加到适配器的同时调用setSelection,请参阅以下示例:How to avoid onItemSelected to be called twice in Spinners