Prevent EditText from going to new line when 'Space' is tapped

前提是你 提交于 2020-02-05 04:32:12

问题


I want to have an EditText which is multi Line and First Letter of a Sentence to be capital. I'm using:

<EditText
        android:id="@+id/editText2"
        android:layout_width="300dp"
        android:layout_height="150dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="32dp"
        android:layout_marginTop="67dp"
        android:background="#ddebed"
        android:ems="10"
        android:inputType="textMultiLine|textCapSentences"
        android:singleLine="false"
        android:text="@string/same" />

I can acheive both: MultiLine and CapSentences. But, When I press 'Space key' after a word, It goes to a new line. How do I prevent it?

The android:text="@string/same" refers to <string name="same">\n \n \n Regards: Principal</string> So, The problem is being caused by \n's. I want to have an EditText which has some already typed text in next Line, And Allow User to enter some text in First 'n' lines.


回答1:


Use android:maxLines="1" and android:inputType="text"

Your Edittext should look like below.

<EditText
        android:id="@+id/editText2"
        android:layout_width="300dp"
        android:layout_height="150dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="32dp"
        android:layout_marginTop="67dp"
        android:background="#ddebed"
        android:ems="10"
        android:maxLines="1"
        android:inputType="text|textCapSentences"
        android:text="@string/same" />

OR

If you are looking for multilines you can edit your edittext as

android:inputType="text|textMultiLine|textCapSentences"

Similarly you can increase android:maxLines="2"

I have checked it out. You can use above code with some below modifications.

EditText editText = (EditText)findViewById(R.id.editText2);
editText.setSelection(0);

It will move your cursor to position 0. Also try to increase maxlines value. I have checked it my end and it's working fine.




回答2:


Try using this tag in xml.

android:singleLine="true"



回答3:


You can Add Two Hidden Spaces Before \n's. To add a Hidden space: Alt + 0160 (Numpad keys). So, When User is typing something, The Hidden Spaces will keep moving and UserText won't be able to reach to \n.



来源:https://stackoverflow.com/questions/47446726/prevent-edittext-from-going-to-new-line-when-space-is-tapped

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!