正文
问题很奇怪,此外还发现适配完数据后会默认选中第一个,并且这个默认选中第一个的操作并不是马上执行的,而是一段时候后再执行,并触发OnItemSelectedListener事件。下面直奔主题:
旧代码:
spinner.setAdapter(adapter);
spinner.setSelection( 2 );
spinner.setSelection( 2 );
新代码:
spinner.setAdapter(adapter);
spinner.setSelection( 2 , true );
spinner.setSelection( 2 , true );
在来看setSelection有两个参数的函数重载的说明:
setSelection(int position, boolean animate)
英文:Jump directly to a specific item in the adapter data.
中文:直接跳到数据适配器中指定项。
以下是两个函数的源代码:
/**
* Jump directly to a specific item in the adapter data.
*/
public void setSelection( int position, boolean animate) {
// Animate only if requested position is already on screen somewhere
boolean shouldAnimate = animate && mFirstPosition <= position &&
position <= mFirstPosition + getChildCount() - 1 ;
setSelectionInt(position, shouldAnimate);
}
@Override
public void setSelection( int position) {
setNextSelectedPositionInt(position);
requestLayout();
invalidate();
}
* Jump directly to a specific item in the adapter data.
*/
public void setSelection( int position, boolean animate) {
// Animate only if requested position is already on screen somewhere
boolean shouldAnimate = animate && mFirstPosition <= position &&
position <= mFirstPosition + getChildCount() - 1 ;
setSelectionInt(position, shouldAnimate);
}
@Override
public void setSelection( int position) {
setNextSelectedPositionInt(position);
requestLayout();
invalidate();
}
本文转自over140 51CTO博客,原文链接:http://blog.51cto.com/over140/582222,如需转载请自行联系原作者