当所选项目发生变化时,如何为微调器设置事件侦听器?

基本上我想做的是类似这样的事情:

spinner1.onSelectionChange = handleSelectionChange;

void handleSelectionChange(Object sender){
    //handle event
}

spinner1.setOnItemSelectedListener(
    new AdapterView.OnItemSelectedListener() {
        //add some code here
    }
);

spinner-widget的文档说

旋转器不支持项目单击事件。

您应该使用setOnItemSelectedListener来处理您的问题。


前面的一些答案是不正确的。它们适用于其他小部件和视图,但Spinner小部件的文档明确指出:

旋转器不支持项目单击 事件。调用此方法将引发 一个例外。

最好使用OnItemSelectedListener()代替:

spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
        // your code here
    }

    @Override
    public void onNothingSelected(AdapterView<?> parentView) {
        // your code here
    }

});

这对我很有用。

注意,onItemSelected方法也被调用时,视图正在构建,所以你可以考虑把它放在onCreate()方法调用。


Spinner spnLocale = (Spinner)findViewById(R.id.spnLocale);

spnLocale.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { 
        // Your code here
    } 

    public void onNothingSelected(AdapterView<?> adapterView) {
        return;
    } 
}); 

注意:记住一件事。

OnItemSelectedListener事件将执行两次:

旋转器初始化 手动选择的用户

试着用标志变量来区分这两者。


https://stackoverflow.com/q/1714426/811625

你可以通过一个简单的检查来避免OnItemSelectedListener()被调用:将当前的选择索引存储在一个整数变量中,并在做任何事情之前在onItemSelected(..)中进行检查。

E.g:

Spinner spnLocale;

spnLocale = (Spinner)findViewById(R.id.spnLocale);

int iCurrentSelection = spnLocale.getSelectedItemPosition();

spnLocale.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { 
    if (iCurrentSelection != i){
            // Your code here
    }
    iCurrentSelection = i;
    } 

    public void onNothingSelected(AdapterView<?> adapterView) {
        return;
    } 
}); 

当然,iCurrentSelection应该在对象范围内,这样才能工作!


我认为最好的方法是让flagitemselected = 0;在onCreate()。在itemselected event上增加标志,即flagitemselected++;然后检查

if(flagitemselected!=1)
{
// do your work here
}

我想这会有帮助。


我发现的一个技巧是把你的setOnItemSelectedListeners放在onWindowFocusChanged而不是onCreate中。我还没有发现这样做有任何副作用。基本上,在窗口绘制之后设置侦听器。我不确定onWindowFocusChanged运行的频率,但如果你发现它运行得太频繁,创建一个锁变量是很容易的。

我认为Android可能会使用基于消息的处理系统,如果你把它都放在onCreate中,你可能会遇到旋转器在它被绘制后被填充的情况。你的监听器会在你设置项目位置后启动。当然,这是一个有根据的猜测,但请随意纠正我。


找到你的微调器名称和id,然后实现这个方法。

spinnername.setOnItemSelectedListener(new OnItemSelectedListener() {

    @Override
    public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
        // your code here
    }

    @Override
    public void onNothingSelected(AdapterView<?> parentView) {
        // your code here
    }
});

您可以实现AdapterView。Activity中的OnItemSelectedListener类。

然后在onCreate()中使用下面的行

Spinner spin = (Spinner) findViewById(R.id.spinner);
spin.setOnItemSelectedListener(this);

然后重写这两个方法:

public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
    selection.setText(items[position]);
}

public void onNothingSelected(AdapterView<?> parent) {
    selection.setText("");
}

spinner.setOnItemSelectedListener(
            new AdapterView.OnItemSelectedListener() {

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

                    // TODO Auto-generated method stub
                }

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

                }
                //add some code here
            }
        );

为当前旋转器的选择取一个全局变量:

int currentItem = 0;

spinner_counter = (Spinner)findViewById(R.id.spinner_counter);
String[] value={"20","40","60","80","100","All"};
aa=new ArrayAdapter<String>(this,R.layout.spinner_item_profile,value);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner_counter.setAdapter(aa);

spinner_counter.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            if(currentItem == position){
                return; //do nothing
            }
            else
            {
                 TextView spinner_item_text = (TextView) view;
                 //write your code here
            }
            currentItem = position;
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

//R.layout.spinner_item_profile
<?xml version="1.0" encoding="utf-8"?>

<TextView  android:id="@+id/spinner_item_text"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" 
android:layout_height="wrap_content"
android:background="@drawable/border_close_profile"
android:gravity="start"  
android:textColor="@color/black"         
android:paddingLeft="5dip"
android:paddingStart="5dip"
android:paddingTop="12dip"
android:paddingBottom="12dip"
/>

//drawable/border_close_profile
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
  <item>
   <shape android:shape="rectangle">
    <solid android:color="#e2e3d7" />
   </shape>
 </item>
<item android:left="1dp"
android:right="1dp"
android:top="1dp"
android:bottom="1dp">
<shape android:shape="rectangle">
    <solid android:color="@color/white_text" />
</shape>
</item>
</layer-list>

你在onCreate或onStart中设置OnItemSelectedListener并不重要——它仍然会在活动创建或启动期间被调用(分别)。 所以我们可以在onCreate中设置它(而不是在onStart中!) 只需添加一个标志来计算第一次初始化:

private Spinner mSpinner;
private boolean mSpinnerInitialized;

然后在onCreate(或onCreateView)中只需:

mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                if (!mSpinnerInitialized) {
                    mSpinnerInitialized = true;
                    return;
                }

                // do stuff
            }

            public void onNothingSelected(AdapterView<?> adapterView) {
                return;
            }
        });

如果你想要一个true onChangedListener()。将初始值存储在处理程序中,并检查它是否已更改。它很简单,不需要全局变量。如果页面上有多个转轮,则有效。

String initialValue = // get from Database or your object
mySpinner.setOnItemSelectedListener(new SpinnerSelectedListener(initialValue));

...

protected class SpinnerSelectedListener implements AdapterView.OnItemSelectedListener {

        private SpinnerSelectedListener() {
            super();
        }

        public SpinnerSelectedListener(String initialValue) {
            this();
            this.initialValue = initialValue;
        }

        private String initialValue;

        // getter and setter removed.  

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            final String newValue = (String) spinHeight.getItemAtPosition(position);
            if (newValue.equals(initialValue) == false) {
               // Add your code here.  The spinner has changed value. 

               // Maybe useful.   
               // initialValue = newValue;
            }

        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
               // Maybe useful.   
               // initialValue = null; 
        }
    }

对象是你的朋友,使用它们。


这是可行的 初始化旋转器和findviewbyid并使用它将工作

    Spinner schemeStatusSpinner;

  schemeStatusSpinner = (Spinner) dialog.findViewById(R.id.spinner);

schemeStatusSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
            // your code here
            if(schemeStatusSpinner.getSelectedItemId()==4){
                reasonll.setVisibility(View.VISIBLE);
            }
            else {
                reasonll.setVisibility(View.GONE);
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parentView) {
            // your code here
        }

    });

默认情况下,您将获得旋转器数组的第一项

value = spinner.getSelectedItem().toString();

无论何时你在旋转器中选择值,它都会给你选择的值

如果你想要选定项目的位置,然后这样做

pos = spinner.getSelectedItemPosition();

以上两个答案均为不应用监听器的情况


对于kotlin,您可以使用:

spinner.onItemSelectedListener =  object : AdapterView.OnItemSelectedListener {
    override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
        
    }

    override fun onNothingSelected(p0: AdapterView<*>?) {
        
    }
}

注意:对于onItemSelected方法的参数,我使用自定义变量名


我知道这个问题解决了很长时间,但我有一个“请选择”字符串在我的字符串数组的顶部。然后,当您编写侦听器时

yourspinner.onItemSelectedListener = object : OnItemSelectedListener {
            override fun onItemSelected(adapterView: AdapterView<*>?, view: View, i: Int, l: Long) {
                yourvalue = yourspinner.getSelectedItem().toString()

                when(yourvalue){
                    "Please Select" -> // DO nothing
                    else -> // Do something
                }
            }

            override fun onNothingSelected(adapterView: AdapterView<*>?) {
                return
            }
        }

当然,您可以扩展when语句以拥有不同的响应或操作。