猿问

Android旋转器:获取选定的项更改事件

Android旋转器:获取选定的项更改事件

当所选项发生更改时,如何为旋转器设置事件侦听器?

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

spinner1.onSelectionChange = handleSelectionChange;void handleSelectionChange(Object sender){
    //handle event}


繁花不似锦
浏览 316回答 3
3回答

隔江千里

以前的一些答案是不正确的。它们适用于其他小部件和视图,但用于旋转小部件明确指出:旋转器不支持项目单击事件。调用此方法将引发异常。更好地利用OnItemSelectedListener()相反:spinner.setOnItemSelectedListener(new&nbsp;OnItemSelectedListener()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;@Override &nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;void&nbsp;onItemSelected(AdapterView<?>&nbsp;parentView,&nbsp;View&nbsp;selectedItemView,&nbsp;int&nbsp;position,&nbsp;long&nbsp;id)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;your&nbsp;code&nbsp;here &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;@Override &nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;void&nbsp;onNothingSelected(AdapterView<?>&nbsp;parentView)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;your&nbsp;code&nbsp;here &nbsp;&nbsp;&nbsp;&nbsp;}});这对我有用。注意,在构建视图时也会调用onItemSelected方法,因此可以考虑将其放入其中onCreate()方法呼叫。

LEATH

Spinner&nbsp;spnLocale&nbsp;=&nbsp;(Spinner)findViewById(R.id.spnLocale);spnLocale.setOnItemSelectedListener(new&nbsp;AdapterView.OnItemSelectedListener()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;void&nbsp;onItemSelected(AdapterView<?>&nbsp;adapterView,&nbsp;View&nbsp;view,&nbsp;int&nbsp;i,&nbsp;long&nbsp;l)&nbsp;{&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;Your&nbsp;code&nbsp;here &nbsp;&nbsp;&nbsp;&nbsp;}&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;void&nbsp;onNothingSelected(AdapterView<?>&nbsp;adapterView)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return; &nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;});注:记住一件事。纺纱机OnItemSelectedListener事件将执行两次:旋转初始化用户手动选择尝试使用标志变量来区分这两者。

吃鸡游戏

你可以实现AdapterView.OnItemSelectedListener在你的活动中上课。然后在onCreate()Spinner&nbsp;spin&nbsp;=&nbsp;(Spinner)&nbsp;findViewById(R.id.spinner);spin.setOnItemSelectedListener(this);然后重写这两个方法:public&nbsp;void&nbsp;onItemSelected(AdapterView<?>&nbsp;parent,&nbsp;View&nbsp;v,&nbsp;int&nbsp;position,&nbsp;long&nbsp;id)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;selection.setText(items[position]);}public&nbsp;void&nbsp;onNothingSelected(AdapterView<?>&nbsp;parent)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;selection.setText("");}
随时随地看视频慕课网APP

相关分类

Android
我要回答