进入活动后会自动选择微调项目。我该如何避免这种情况?
我的 Android 应用程序中有一个微调器,其 onItemSelected()
事件在进入 Activity 时自动触发。
我该如何避免这种情况?
I have a spinner in my Android app, and its onItemSelected()
event automatically gets triggered upon entering the activity.
How do I avoid this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
我们可以使用一个标志,并在真正触摸旋转器时启用它。
We can use a flag, and just enable it when the spinner is really touched.
要添加 Jerry Abraham,您应该在启用 setOnItemSelectedListener 之前清除选择
To add on Jerry Abraham, You should clear selection before enabling setOnItemSelectedListener
我已经解决了这个问题,
您可以通过不为微调器设置任何默认值来避免此问题
这将避免进入 onItemSelected()
I have solved this issue,
You can avoid this issue by not setting any default values to the spinner
This will avoid entering into onItemSelected()
没有任何办法可以避免这种情况。
您可以添加一些标志,指示您的应用程序已准备就绪,并在 onItemSelected() 方法中使用它来决定在每种情况下要做什么。
There are no any way to avoid this.
You may add some flag, indicating readiness of your application and use it in your onItemSelected() method to decide, what to do in each case.
那么,您可以向初始适配器添加一个虚拟选择,并忽略 setOnItemSelectedListener 中的位置号。它不漂亮,但很有效。请参阅此代码以设置阵列适配器的项目。
然后在您的
setOnItemSelectedListener
中您可以执行以下操作:Well, you can add a dummy selection to the initial adapter, and ignore position number in the
setOnItemSelectedListener
. It's not pretty but it works. See this code for setting up the items for an array adapter.Then in your
setOnItemSelectedListener
you can do this:我找到了这个问题的解决方案并将其发布在这里(带有代码示例):
Spinner onItemSelected() 在不应该执行的时候执行
I have found a solution for this problem and posted it here (with code sample):
Spinner onItemSelected() executes when it is not suppose to
简单又容易,就是这样……
使用布尔值进行验证,看看是否是第一次...
检查此 with spinner.post(new Runnable()...)
或其他我的来源
Simple and easy is this...
validate with a boolean to see if is first time...
Check this with spinner.post(new Runnable()...)
or this other my source
我认为您可以使用微调器位置,我认为这是更好的方法。
创建一个全局变量来存储微调器位置,在 onItemSelected 方法中提供位置,您可以比较它们,如果它们相同,则不执行操作。
I think that you can use spinner position which is a better approach in my opinion.
Create a global variable where you store the spinner position, in onItemSelected method the position is provided you can compare them, if they are the same do not make an action.
您可以通过忽略第一次点击来避免它,
You can avoid it by ignoring the first click by,