zoukankan      html  css  js  c++  java
  • [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文档还没有翻译到这里,不然少走这个弯路了 :)

  • 相关阅读:
    POJ1239
    HDU 2829 四边形不等式优化
    返回数字二进制的最高位位数o(n)
    矩阵快速幂 模板
    HDU4718 The LCIS on the Tree(LCT)
    HDU4010 Query on The Trees(LCT)
    HDU3487 Play With Chains(Splay)
    CF444C DZY Loves Colors
    HDU4836 The Query on the Tree(树状数组&&LCA)
    HDU4831&&4832&&4834
  • 原文地址:https://www.cnblogs.com/over140/p/1834469.html
Copyright © 2011-2022 走看看