Android EditText回车不换行

来源:互联网 发布:安防视频监控网络平台 编辑:程序博客网 时间:2024/05/21 19:50

先上布局一个EditText添加imeOptions监听回车事件

             <EditText                    android:id="@+id/et_release_experience_input_tag"                    android:layout_marginTop="10dp"                    android:layout_marginBottom="5dp"                    android:layout_width="wrap_content"                    android:layout_height="wrap_content"                    android:imeOptions="actionDone"                    android:layout_gravity="center_horizontal"                    android:hint="添加标签"                    android:maxLines="1"                    android:textColorHint="@color/gray"                    android:textCursorDrawable="@null" />

setOnEditorActionListener实现此回调事件,当事件时event.getKeyCode()为KeyEvent.KEYCODE_ENTER时为回车事件,返回true,表示我们处理此事件,这样回车就不会换行了。

etInputTag.setOnEditorActionListener(new TextView.OnEditorActionListener() {            @Override            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {//回车时返回true拦截事件,不让换行                if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {                    if (TextUtils.isEmpty(etInputTag.getText().toString().trim())) {                        CommonUtils.showToast(ReleaseExperienceActivity.this, "请先输入标签!");                    } else {//不为空时才添加标签                        tagLists.add(etInputTag.getText().toString());                        mAdapter.clearAndAddAll(tagLists);                        etInputTag.setText("");                    }                    return true;                }                return false;            }        });
1 0