android Spinner 重新填充資料後 setSelection 總顯示第一項

來源:互聯網
上載者:User

        當在做兩個spinner聯動時,spinner2依據spinner1的選擇填充資料,然後使用setSeletion(2)來設定預設項。結果發現:spinner2顯示的總是第一項,但是實際選擇的確實已經是position 2的位置 。

  解決方案:

  舊代碼:

  spinner.setAdapter(adapter);

  spinner.setSelection(2);

         解決方案有二:

  (1)

  spinner.setAdapter(adapter);

  spinner.setSelection(2,true);  //spinner會重新layout

       (2) 推薦

      
spinner.setAdapter(adapter);

  adapter.notifyDataSetChanged();       //通知spinner重新整理資料

       spinner.setSelection(2);

        那麼,這到底是什麼原因造成的?我認為這是一個bug 。這種情況通常發生在重新填充資料之後,除此之外,使用setSelection(int position)都能得到正確的顯示。

       setSelection(int position, boolean animate)和setSelection(int position) 實現機制有較大區別,當調用前者時重新layout,立即觸發onItemSelected函數,作用相當於用手直接點擊。而後者設定了下次選擇位置:setNextSelectedPositionInt(position); 然後請求Layout;,而requestLayout並非立即執行,僅僅是一個schedule。但是後者可能在重新裝載資料然後Layout時丟失了某些狀態。

      

BTW : 一篇介紹比較詳細的spinner總結 http://www.blogjava.net/crazycoding/archive/2011/07/09/353981.html

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.