为什么在Spinner中调用notifyDataSetChanged()时调用OnItemClick?

时间:2014-04-28 08:54:57

标签: android android-layout android-fragments android-listview

更新微调器适配器时遇到问题。我有一个微调器,当onItem点击微调器我更新了TextView。每当我通过调用adapet.notifyDataSetChanged()更新微调器列表时,onItemSelected Lisener会在不选择微调器的情况下自动调用。为什么会这样?我在这里分享了一些代码的和平

这是用于更新带列表的适配器

 if(mEmailList == null){
   mEmailList = new ArrayList<String>();
 }
 mEmailList.clear();
 for(int i =0 ; i < responseArray.length() ; i++){
   responseObj = responseArray.getJSONObject(i);
   String collected_email = "";
   collected_email = Utils.getDataFromJSON(responseObj, "eMail");
   if(Utils.isHavingValue(collected_email.trim())){
      mEmailList.add(collected_email);
    }
  }
  if(emailAdapter != null){
      if(mActivity != null){
        mActivity.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            emailAdapter.notifyDataSetChanged();
        }
       });
   }
}

这是onItenSelectionListener

if(mEmail_spinner != null && emailAdapter != null){
   mEmail_spinner.setAdapter(emailAdapter);
   mEmail_spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
   @Override
   public void onItemSelected(AdapterView<?> arg0,View arg1, int arg2,long arg3) {
      Log.d(TAG, "On ItemSelect called Adapter = "+arg0+"    View = "+arg1+" value "+arg2);
      if(Utils.isHavingValue(arg0.getItemAtPosition(arg2).toString())){
     if(mEmailReg != null){
       mEmailReg.setText(arg0.getItemAtPosition(arg2).toString());
    }
    @Override
    public void onNothingSelected(
    AdapterView<?> arg0) {
    Log.d(TAG, "On Nothing selected called Adapter = "+arg0);
    if(mEmailReg != null){
    //   mEmailReg.setText(mPreviousText);
        }
   });
}

从不调用notifyDataSetChanged()调用List ItemClickListener alson。怎么避免这个?

2 个答案:

答案 0 :(得分:0)

更改

mEmail_spinner.setAdapter(emailAdapter);

mEmail_spinner.setOnItemSelectedListener(null);
mEmail_spinner.setAdapter(emailAdapter);

通过这种方式,如果您已将“OnItemSelectedListener分配给mEmail_spinner,则在致电notifyDataSetChanged();时将无法呼叫

致电onItemSelectedListener

后再次设置setAdapter

答案 1 :(得分:0)

正在发生这种情况,因为适配器已更新。旧项目已消失,新项目已添加,因此微调器具有新选定项目。这就是调用onItemClick方法的原因。