可能重复: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”键,光标也不能下到第二行。有人能帮我一下吗?


当前回答

对我来说,我这样做,去你的textView在xml文件,并添加这两行

' android:maxLines=“1”

android:inputType=“text”'

其他回答

@Aleks G OnKeyListener()工作得很好,但我从MainActivity运行它,所以必须稍微修改一下:

EditText searchBox = (EditText) findViewById(R.id.searchbox);
searchBox.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) MainActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(searchBox.getApplicationWindowToken(), 0);

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

            return true;
        }

        return false;
    }
});

我希望这篇文章能帮助到那些想做同样事情的人。

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

对我来说,我这样做,去你的textView在xml文件,并添加这两行

' android:maxLines=“1”

android:inputType=“text”'

为了限制你只需要设置单行选项为“真”。

android:singleLine="true"

同样重要的是要注意属性android:inputType是否为textMultiLine。如果是这样,属性android:singleLine, android:imeOptions, android:ellipsize和android maxLines将被忽略,你的EditText将接受MultiLines无论如何。