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()。 这意味着代码被过早地执行;仅在用户实际做出选择时才会执行的代码。
解决方案
- 在 onCreate() 中,计算 View 中有多少个 Gallery(或 Spinner)小部件。 (mGalleryCount)
- 在 onItemSelected() 中,计算它触发的频率。 (mGalleryInitializedCount)
- 当 (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/