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

▼魔方 西西 提交于 2020-01-07 03:24:07

问题


I am looking to create an edit text with a 3-4 line hint which on click, allows the user to enter only a single line of text. I have tried to use

android:singleLine = "true"

But that limits the length of the hint as well.

How do I assign different number of lines for both ?

Thanks


回答1:


You could add a TextWatcher to your edit text and compare the length of the text. If it is 0, then the hint is shown and you programmatically set editText.setSingleLine(false). If it is greater than 0, you restrict the editText with setSingleLine(true).

Pseudocode:

    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);
        }
    });
}



回答2:


try this:

<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>



回答3:


Set textview property programatically like this :

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);
   }
 }
});


来源:https://stackoverflow.com/questions/31832665/android-how-to-create-edit-text-with-single-line-input-and-multiline-hint

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