[Android]为Spinner填充数据后设置默认值的问题


前言

   为Spinner适配完数据后需要设置其默认选项,但是发现直接setSelection(int position)有时候不管用,打开选项又发现已经选中了,但是显示出来的选项又始终默认第一个,本文为文章1的中文简单译本。

 

文章

  1.  Using spinner.setSelection & finding the spinner doesn't show the selected item when closed?

 

声明

  欢迎转载,但请保留文章原始出处:)

    博客园:http://www.cnblogs.com

    农民伯伯: http://www.cnblogs.com/over140/

 

正文

  问题很奇怪,此外还发现适配完数据后会默认选中第一个,并且这个默认选中第一个的操作并不是马上执行的,而是一段时候后再执行,并触发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文档还没有翻译到这里,不然少走这个弯路了 :)

posted @   农民伯伯  阅读(84026)  评论(6编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
点击右上角即可分享
微信分享提示