Android Spinner:选择同一项时不调用onItemSelected侦听器

时间:2015-07-31 09:36:37

标签: android listener android-spinner

我需要在AlertDialog中选择第二项时显示Spinner。我知道使用onItemSelected我们可以听到微调器选择&显示一个弹出窗口。问题是当我选择第二个项目时,会出现对话框,但在关闭对话框后再次选择相同的项目时,它不会显示对话框,因为onItemSelected将不会被调用。这有什么解决方法吗?不使用自定义Spinner实现。

2 个答案:

答案 0 :(得分:3)

创建自定义微调器

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Spinner;

public class CustomSpinner extends Spinner {
    OnItemSelectedListener listener;
    private AdapterView<?> lastParent;
    private View lastView;
    private long lastId;

    public CustomSpinner(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
        initlistner();
    }

    @Override
    public void setSelection(int position) {
        if (position == getSelectedItemPosition() && listener != null) {
            listener.onItemSelected(lastParent, lastView, position, lastId);
        } else {
            super.setSelection(position);
        }

    }

    private void initlistner() {
        // TODO Auto-generated method stub
        super.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                    int position, long id) {
                // TODO Auto-generated method stub
                lastParent = parent;
                lastView = view;
                lastId = id;
                if (listener != null) {
                    listener.onItemSelected(parent, view, position, id);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // TODO Auto-generated method stub
                if (listener != null) {
                    listener.onNothingSelected(parent);
                }
            }
        });

    }

    public void setOnItemSelectedEvenIfUnchangedListener(
            OnItemSelectedListener listener) {
        this.listener = listener;
    }

}

设置监听器

private OnItemSelectedListener listener;

listener = new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1,
                int arg2, long arg3) {}

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub

        }
    };

将侦听器对象传递给自定义侦听器

cusSpinner.setOnItemSelectedEvenIfUnchangedListener(listener);

答案 1 :(得分:-3)

尝试下面的代码:

spinner.setOnItemSelectedListener(this);

@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) 
{
     switch(arg2)
     {
          case 0:
          {
               Dialog dialog = new Dialog(getApplicationContext());
               .......
               dialog.show();
               spinner.setSelection(0);
          }
          break;
     }
[...]