如何实现可选择复制但不可编辑的多行EditText?
How to Create a Selectable, Non-Editable Multi-Line EditText
Hey there! I’ve dealt with this exact scenario before, so let me break down the reliable solutions for you. The issue with your initial textMultiLine|none approach is that none maps to InputType.TYPE_NULL, which forces the EditText into single-line mode—exactly why your multi-line behavior broke.
Here are two solid ways to get a multi-line, selectable-but-uneditable EditText:
Solution 1: XML + Code (Recommended for Compatibility)
First, set up your EditText in XML with the multi-line input type, then disable editing via code while preserving selectability:
XML Layout
<EditText android:id="@+id/readOnlyMultiLineEditText" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textMultiLine" android:scrollbars="vertical" <!-- Optional: adds scroll for long content --> android:text="Your multi-line text here\nSecond line of content\nThird line to test wrapping" />
Java Code
EditText readOnlyEditText = findViewById(R.id.readOnlyMultiLineEditText); // Disable editing while keeping selectability readOnlyEditText.setKeyListener(null); // Ensure long press brings up copy/select menu readOnlyEditText.setLongClickable(true); // Optional: Hide cursor if you don't want it visible readOnlyEditText.setCursorVisible(false);
Kotlin Code
val readOnlyEditText = findViewById<EditText>(R.id.readOnlyMultiLineEditText) readOnlyEditText.keyListener = null readOnlyEditText.isLongClickable = true readOnlyEditText.isCursorVisible = false // Optional
Solution 2: Pure XML (Simpler, Note Compatibility)
You can also use XML attributes directly, though note that android:editable is marked as deprecated (but still works on most devices):
<EditText android:id="@+id/readOnlyMultiLineEditText" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textMultiLine" android:editable="false" android:longClickable="true" android:scrollbars="vertical" android:text="Multi-line content\nthat's easy to select\nbut impossible to edit" />
Why This Works
textMultiLinekeeps the line-wrapping and multi-line behavior intact.- Disabling the key listener (or using
editable="false") prevents any text input. longClickable="true"ensures users can trigger the text selection menu to copy content.
内容的提问来源于stack exchange,提问作者rcorbellini
相关产品推荐
相关产品推荐

