我有运行spinner的OnItemSelectedListener
事件的代码。所以当我在方法中时:
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// I want to do something here if it's a user who changed the the selected item
}
字符串
.我如何知道项目选择是通过编程完成的还是通过UI由用户操作完成的?
7条答案
按热度按时间hk8txs481#
我不知道这是否可以从方法内部区分出来。事实上,这是很多人面临的一个问题,当微调器被启动时,
onItemSelected
被触发。目前看来,唯一的解决办法是使用外部变量。字符串
nmpmafwu2#
使用Spinner的
setOnTouchListener()
方法可以相当简单地实现所需的结果:字符串
1dkrff033#
我做了一个新的Spinner类封装了上面提到的原则。
在gist中也是如此
字符串
uelo1irk4#
我已经想出了一个简单而通用的解决方法。请参考这个问题的公认答案:
不需要的onItemSelected调用
因此,如果
position
不等于spin.getTag(R.id.pos)
,那么您知道回调是由于用户进行了更改,因为无论何时您自己进行更改,您都将标记设置为spin.setTag(R.id.pos, pos)
,其中pos是您设置的值。如果您使用这种方法,请确保在完成工作后在onItemSelected
中设置标记!nnt7mjpx5#
与
SeekBar
不同,Spinner
没有内置的支持来检测更改是程序性的还是用户的,所以我建议,我从来不使用spinner来完成任何递归编程任务。当我试图实现一个MediaPlayer
与一个SeekBar
和一个Spinner
的递归连接时,我有过非常糟糕的经历。结果令人失望。所以,只有当你喜欢不快乐和失望时,你才能尝试。**注意:**我通过添加apply
Button
到我的微调器选择来解决我的问题。做一个工作不是一个好的做法,而是重新实现Spinner
以具有我们自己的预期行为。bybem2ql6#
我做了一个@ban-geoengineering和@vedant的mashup。
我不喜欢
isUserAction
的答案。@ban-geoengineering的答案对一个Spinner来说很可爱,但当你有多个Spinner时就不可爱了。
我不喜欢在@vedant的答案中需要一个特殊的
changeSpinnerSelectionProgrammatically
方法。我认为这是一个合理的两全其美:
字符串
kg7wmglp7#
我使用了一个基于触摸模式下可聚焦的解决方案。
1.在触摸模式下将微调器视图设置为可聚焦。
1.设置微调器的焦点改变监听器,以便在焦点改变时调用微调器.performClick()。
1.在微调器的onItemSelected侦听器中,将焦点返回到布局的父视图(或您认为合适的视图)
1.用户输入可以通过检查微调器是否具有焦点来识别,因为编程更改不会请求焦点。
附言:当你在onCreate中为微调器设置focusableintouchmode时,确保你立即将焦点返回到父视图,以防你缺少任何其他可聚焦的视图。