Android 如何使用单行输入和多行提示创建编辑文本

Android how to create edit text with single line input and multiline hint

我想创建一个带有 3-4 行提示的编辑文本,单击该提示后,用户只能输入一行文本。 我尝试使用

android:singleLine = "true"

但这也限制了提示的长度。

如何为两者分配不同的行数?

谢谢

试试这个:

<EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:maxLines="1"
        android:hint="your hint here your hint here your hint here your hint here  your hint here your hint here your hint here your hint here your hint here your hint here "
        android:ems="10" >

        <requestFocus />
    </EditText>

您可以将 TextWatcher 添加到您的编辑文本并比较文本的长度。 如果它是 0,则显示提示并且您以编程方式设置 editText.setSingleLine(false)。如果它大于 0,则使用 setSingleLine(true) 限制 editText。

伪代码:

    public void some(){
    final EditText t = findViewById(someName);
    t.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            t.setSingleLine(t.getText().toString().length() > 0);
        }
    });
}

像这样以编程方式设置 textview 属性 :

myText.setOnFocusChangeListener(new OnFocusChangeListener() {

 @Override
 public void onFocusChange(View v, boolean hasFocus) {
    // TODO Auto-generated method stub
    if(hasFocus){
        myText.setSingleLine(true);
        //myText.setMaxLines(1);
       // myText.setLines(1);
    }
   else if(myText.matches(""))
   {
      myText.setSingleLine(false);
   }
 }
});