Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android EditText 實現唯讀(不可編輯)的簡潔做法

編輯:Android 開發實例

如果你曾用過 android:editable 屬性,編譯時應該會看到這兩段警告:

android:editable is deprecated: Use an <EditText> to make it editable
android:editable is deprecated: Use inputType instead

這個屬性在早期 SDK 可用,如今已被標記為不建議使用。

需求是什麼

這裡要解決的是「唯讀」情境:使用者無法透過 UI 修改 EditText 中的內容,但仍然可以選取部分文字進行複製。這種需求在顯示關鍵資訊(例如訂單編號、驗證碼)時相當常見。

一行程式碼解決

et.setKeyListener(null);

注意是 setKeyListener,不是 setOnKeyListener。這是 TextView 的成員方法,效果完全符合預期,而且取得焦點後不會彈出輸入法。

官方文件的說法

Sets the key listener to be used with this TextView. This can be null to disallow user input. Note that this method has significant and subtle interactions with soft keyboards and other input method: see KeyListener.getContentType() for important details. Calling this method will replace the current content type of the text view with the content type returned by the key listener.

Be warned that if you want a TextView with a key listener or movement method not to be focusable, or if you want a TextView without a key listener or movement method to be focusable, you must call setFocusable again after calling this to get the focusability back the way you want it.

文件中特別提醒:傳入 null 就是為了禁止使用者輸入;而如果你希望調整焦點行為,記得在呼叫之後再明確設定一次 setFocusable()。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved