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

解決 android:editable 已棄用:讓 EditText 變成唯讀的正确做法

編輯:關於 Android 程式設計

編譯時跳出一段警告:

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

意思是說 android:editable 這個屬性已經被反對使用了,要控制能不能編輯,請直接改用 EditText 本身的屬性。

問題場景

需求是讓某個輸入框變成 read-only:使用者無法透過鍵盤改內容,但仍可以選取部分文字複製。早期 SDK 的 EditText 有 editable 屬性可以辦到,但這個屬性後來被標記為 deprecated,於是就出現了上面那則警告。

解決方法:一行程式碼

et.setKeyListener(null);

就這樣,一行搞定。這裡有個非常容易寫錯的地方:是 setKeyListener,不是 setOnKeyListener。前者是 TextView 的成員方法,作用是決定「用哪個鍵盤傾聽器」,傳入 null 就等於禁止使用戶輸入;後者是用來監聽按鍵事件的,兩者完全不同。

這個做法的效果完全符合預期:欄位取得焦點後不會彈出輸入法,文字也無法被修改,但選取與複製照常可用。

官方文件怎麼說

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 methods: 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.

最後一句話是實務上最容易忽略的提醒:呼叫 setKeyListener 會連帶改變 focusable 的行為。如果你發現設定完之後焦點狀態不如預期,記得在後面補一次 setFocusable() 把它調回來。

另一個常見做法

若你比較喜歡在 XML 裡處理,也可以給 EditText 加上 android:focusable="false"、或搭配 android:cursorVisible="false" 與 android:longClickable="false" 來達到類似效果。不過論「保持可選取複製、只是不能編輯」這個精確需求,setKeyListener(null) 仍然是最乾淨的答案。

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