Android EditText控件完美實現隻讀(Read-Only/Non-Editable)
很多朋友困惑於EditText控件的read-only問題, 包括我. Read-only在這裏的定義等同於win32 edit控件的read-only, 即: 無法通過UI更改其中的內容, 但可以選定部分內容, 進行複製.
在早期的sdk, EditText有Editable屬性(至於這個屬性是否有用, 沒有測過, 本人入門較晚, 沒使用過早期sdk), 現在這個屬性已經deprecated了. 網上有大量關於此問題的內容, 要麼是掩耳盜鈴式的設成non-focusable, 要麼是複雜的TextWatch, 始終沒有發現簡潔完美的方法. 當初曾被此問題折騰得夠嗆, 甚至用WebView替代過. 其實隻需一行代碼就能搞定
et.setKeyListener(null);
注意, 這裏不是setOnKeyListener, 而是setKeyListener. 此方法是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.
我想, 這也應該是官方方法了, 納悶為啥網上搜不出來這種解決方法.
另外, setOnKeyListener其實也是可以的
et.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { return true; } }); //consume key input et.setInputType(InputType.TYPE_NULL);//禁止輸入法
這種方法隻經過粗略測試, 無法確定是否與前一種等價. 既然已經有完美方法了, 忘了它吧.
最後更新:2017-04-04 07:03:41