zl程序教程

您现在的位置是:首页 >  移动开发

当前栏目

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

Android数据 设置 填充 默认值 问题 spinner
2023-09-14 09:00:58 时间

前言

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

 

文章

1. Using spinner.setSelection finding the spinner doesnt 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文档还没有翻译到这里,不然少走这个弯路了 :)


转载:http://www.cnblogs.com/over140/archive/2010/09/25/1834469.html