Android編程之TextView的字元過濾功能分析_Android

來源:互聯網
上載者:User

本文執行個體分析了Android編程之TextView的字元過濾功能。分享給大家供大家參考,具體如下:

TextView可以設定接受各式各樣的字元,通過過濾指定的字元來滿足不同應用的輸入和顯示要求。

通過xml配置:

android:InputType

number          接受整數輸入
numberSigned    接受有符號整數輸入
numberDecimal   接受整數和小數的輸入

android:digits

指定接受固定的數字,如android:digits="012345",則只接受0~5數位輸入

android:numberic

integer   接受整數輸入
signed    接受有符號整數輸入
decimal   接受整數和小數輸入

通過java代碼設定

其實以上3個屬性,功能有點重複,最終都是通過java代碼來對TextView設定KeyListener

KeyListener是一個介面,提供了對輸入鍵盤按鍵的監聽

InputFilter是一個介面,提供了對字元的過濾

android提供了實現了KeyListener和InputFilter的NumberKeyListener,而DigitsKeyListener繼承了NumberKeyListener

TextView tv = new TextView(context);//只接受整數輸入KeyListener l = new DigitsKeyListener(fasle,false);//接受有符號整數輸入KeyListener l = new DigitsKeyListener(true,false);//接受小數,整數輸入KeyListener l = new DigitsKeyListener(false,true);//接受有符號整數/小數輸入KeyListener l = new DigitsKeyListener(true,true);tv.setKeyListener(l);

如果想要實現更大自由度的過濾定製,可以自己寫一個KeyListener(繼承BaseKeyListener)並實現InputFilter,重寫filter()函數,在filter()函數裡可以實現自由的過濾。

希望本文所述對大家Android程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.