Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 讓 EditText 變成不可編輯的解法

編輯:關於 Android 程式設計

在開發中常會看到這樣的提醒:

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

問題分析:關於 EditText 的唯讀(read-only)需求——也就是無法透過 UI 修改內容,但仍能選取部分文字進行複製。早期 SDK 的 EditText 有 Editable 屬性可用,但如今這個屬性已被標記為 deprecated。

解法:其實只需一行程式碼就能搞定:

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.

簡言之,把 KeyListener 設為 null 即可禁止使用者輸入,同時保留選取與複製的能力,是實作唯讀 EditText 最乾淨俐落的做法。

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