可能重复:android- singlline -true-not-working-for edittext

<EditText 
    android:id="@+id/searchbox"  
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:lines="1"
    android:scrollHorizontally="true"
    android:ellipsize="end"
    android:layout_weight="1"
    android:layout_marginTop="2dp"
    android:drawablePadding="10dp"
    android:background="@drawable/edittext"
    android:drawableLeft="@drawable/folder_full"
    android:drawableRight="@drawable/search"
    android:paddingLeft="15dp"
    android:hint="search...">
</EditText>

我想使上面的EditText只有单行。即使用户按下“enter”键,光标也不能下到第二行。有人能帮我一下吗?


当前回答

我已经在过去用android:singleLine="true",然后为"enter"键添加一个监听器:

((EditText)this.findViewById(R.id.mytext)).setOnKeyListener(new OnKeyListener() {

    public boolean onKey(View v, int keyCode, KeyEvent event) {

        if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
            //if the enter key was pressed, then hide the keyboard and do whatever needs doing.
            InputMethodManager imm = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(getApplicationWindowToken(), 0);

            //do what you need on your enter key press here

            return true;
        }

        return false;
    }
});

其他回答

必须在EditText中添加这一行

android:maxLines="1"

还有一件事,不要忘记设置android:inputType(任何你想要的,文本,电话..,但必须设置)

不建议使用android:singleLine="true"。

只需添加您的输入类型并将maxline设置为1,一切都会正常工作

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

编程:

textView.setMaxLines(1);

每个人都展示了XML的方式,只有一个人展示了调用EditText的setMaxLines方法。然而,当我这样做的时候,它并没有起作用。对我来说有用的一件事是设置输入类型。

EditText editText = new EditText(this);
editText.setInputType(InputType.TYPE_CLASS_TEXT);

这允许A-Z、A-Z、0-9和特殊字符,但不允许按enter键。当您按enter键时,它将转到下一个GUI组件(如果在您的应用程序中适用的话)。

你可能还想设置可以放入EditText的最大字符数,否则它会把它右边的内容推到屏幕外,或者只是开始拖到屏幕外。你可以这样做:

InputFilter[] filters = new InputFilter[1];
filters[0] = new InputFilter.LengthFilter(8);
editText.setFilters(filters);

这将该EditText中的最大字符设置为8。希望这些对你有所帮助。

包括android:单行模式= " true "