前言

   为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文档还没有翻译到这里,不然少走这个弯路了 :)
 

更多相关文章

  1. Android中使用SQlite进行数据操作
  2. Android开发中高效的数据结构用SparseArray代替HashMap
  3. Android Preference的使用总结(很全很详细)以及SharedPreferences
  4. 系出名门Android(9) - 数据库支持(SQLite)
  5. [置顶] android 批量插入数据
  6. Android Studio真机调试,数据库sqllite时,Multiple dex files defi
  7. JAVA数据结构及算法--Android中Activity的四种启动模式
  8. UnityAndroid开发(1) 打包和使用Sqlite数据库

随机推荐

  1. ISurfaceComposer接口有13个成员函数
  2. Android 日志系统logcat内核代码分析
  3. ubuntu环境:下载、编译模拟器平台android
  4. Android(2017-2018)BAT面试题整理(java篇,
  5. Android机顶盒 adb命令模拟遥控器操作
  6. Android 常用ADB命令汇总!!! -- 持续补充
  7. Android中 备份短信 还原短信
  8. Animator记录一次属性动画实现的逐渐出现
  9. android链接rest services
  10. Android(安卓)studio修改apk release打包