[Android]为Spinner填充数据后设置默认值的问题
16lz
2021-01-23
前言
为Spinner适配完数据后需要设置其默认选项,但是发现直接setSelection(int position)有时候不管用,打开选项又发现已经选中了,但是显示出来的选项又始终默认第一个,本文为文章1的中文简单译本。
文章
1. Using spinner.setSelection & finding the spinner doesn't show the selected item when closed?
声明
欢迎转载,但请保留文章原始出处:)
农民伯伯: http://over140.blog.51cto.com/
正文
问题很奇怪,此外还发现适配完数据后会默认选中第一个,并且这个默认选中第一个的操作并不是马上执行的,而是一段时候后再执行,并触发OnItemSelectedListener事件。下面直奔主题:
旧代码:
spinner.setAdapter(adapter);spinner.setSelection( 2 );
新代码:
spinner.setAdapter(adapter);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();
}
结束
看起来像是专门准备了一个函数在数据适配(填充)完后设置默认值的,可惜API文档还没有翻译到这里,不然少走这个弯路了 :)
更多相关文章
- Android中使用SQlite进行数据操作
- Android开发中高效的数据结构用SparseArray代替HashMap
- Android Preference的使用总结(很全很详细)以及SharedPreferences
- 系出名门Android(9) - 数据库支持(SQLite)
- [置顶] android 批量插入数据
- Android Studio真机调试,数据库sqllite时,Multiple dex files defi
- JAVA数据结构及算法--Android中Activity的四种启动模式
- UnityAndroid开发(1) 打包和使用Sqlite数据库