java - Spinner onItemSelected() 执行不当

标签 java android

Possible Duplicate:
Android Spinner OnItemSelected Called Erroneously (without user action on opening spinner)

有谁知道在布局实例化时如何防止 onItemSelected()(OnItemSelectedListener 接口(interface))方法运行?我需要知道是否有办法做到这一点,因为我想将我的布局实例化方式与此监听器分开。

我已经尝试创建一个 if 语句,最初设置为 false 围绕被覆盖方法内的所有代码,但无法知道何时将其设置为 true,因为被覆盖的方法在 onCreate() 之后运行,onStart( ) 和 onResume() 方法。

我还没有找到任何明确的答案。任何明确的解决方案将不胜感激。

最佳答案

大卫,这是我为这个问题写的教程...

问题陈述

在 Gallery(或 Spinner)初始化时触发了不受欢迎的 onItemSelected()。 这意味着代码被过早地执行;仅在用户实际做出选择时才会执行的代码。

解决方案

  1. 在 onCreate() 中,计算 View 中有多少个 Gallery(或 Spinner)小部件。 (mGalleryCount)
  2. 在 onItemSelected() 中,计算它触发的频率。 (mGalleryInitializedCount)
  3. 当 (mGalleryInitializedCount < mGalleryCount) == false 时,执行针对用户的代码

代码示例

public class myActivity extends Activity implements OnItemSelectedListener
{
    //this counts how many Gallery's are on the UI
    private int mGalleryCount=0;

    //this counts how many Gallery's have been initialized
    private int mGalleryInitializedCount=0;

    //UI reference
    private Gallery mGallery;


    @Override
    public void onCreate(Bundle savedInstanceState)
    {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.myxmllayout);

        //get references to UI components
        mGallery = (Gallery) findViewById(R.id.mygallery);

        //trap selection events from gallery
        mGallery.setOnItemSelectedListener(this);

        //trap only selection when no flinging is taking place
        mGallery.setCallbackDuringFling(false);

        //
        //do other stuff like load images, setAdapter(), etc
        //

        //define how many Gallery's are in this view
        //note: this could be counted dynamically if you are programmatically creating the view
        mGalleryCount=1;

    }


    public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
    {

        if (mGalleryInitializedCount < mGalleryCount)
        {
            mGalleryInitializedCount++;
        }
        else
        {
            //only detect selection events that are not done whilst initializing
            Log.i(TAG, "selected item position = " + String.valueOf(position) );
        }

    }

}

为什么会这样

此解决方案之所以有效,是因为库在用户实际能够做出选择之前很久就完成了初始化。

关于java - Spinner onItemSelected() 执行不当,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5624825/

相关文章:

java - 在远程计算机上执行 jar 失败

java - 在H2控制台中找不到用JAVA创建的H2数据库?

java - 如何在 Spring-Boot 中配置日志记录框架?

java - 倒计时期间取消按钮

tabbar - Android 中的自定义标签栏

java - 单元测试基础知识 - 到底要测试什么?

android - 计算 Map<String, Map<String, Int>> 中的元素数量?通过它的 key

android语言环境随机更改回默认值

android - 是否有一个选项可以在 android 的 where 子句中传递两个参数来访问 firestore 数据库

android - Gradle同步在Android Studio 3.6中失败