Answers:
我想知道是否有一种方法可以处理用户Enter在输入EditText时的按下操作,例如onSubmit HTML事件。
是。
还想知道是否有一种方法可以操纵虚拟键盘,使“完成”按钮标记为其他名称(例如“转到”),并在单击时执行某种操作(再次类似于onSubmit)。
也可以
您将要查看android:imeActionId
和android:imeOptions
属性以及setOnEditorActionListener()
方法,全部都在上TextView
。
要将“完成”按钮的文本更改为自定义字符串,请使用:
mEditText.setImeActionLabel("Custom text", KeyEvent.KEYCODE_ENTER);
final EditText edittext = (EditText) findViewById(R.id.edittext);
edittext.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// If the event is a key-down event on the "enter" button
if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER)) {
// Perform action on key press
Toast.makeText(HelloFormStuff.this, edittext.getText(), Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
});
enter
编辑文本时,整个编辑文本会向下移动...如何解决此问题?
这就是你要做的。它也隐藏在Android开发人员的示例代码“蓝牙聊天”中。用您自己的变量和方法替换说“示例”的粗体部分。
首先,将所需的内容导入到主活动中,在该活动中您希望返回按钮执行一些特殊的操作:
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;
import android.view.KeyEvent;
现在,为返回键创建一个TextView.OnEditorActionListener类型的变量(这里我使用exampleListener);
TextView.OnEditorActionListener exampleListener = new TextView.OnEditorActionListener(){
然后,您需要告诉收听者有关按下返回按钮时该怎么做的两件事。它需要知道我们在谈论什么EditText(在这里我使用exampleView),然后它需要知道在按下Enter键时该怎么做(在这里为example_confirm())。如果这是活动中的最后一个或唯一的EditText,则它应与“提交”(或“确定”,“确认”,“发送”,“保存”等)按钮的onClick方法相同。
public boolean onEditorAction(TextView exampleView, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_NULL
&& event.getAction() == KeyEvent.ACTION_DOWN) {
example_confirm();//match this behavior to your 'Send' (or Confirm) button
}
return true;
}
最后,设置侦听器(最有可能在您的onCreate方法中);
exampleView.setOnEditorActionListener(exampleListener);
KeyEvent.ACTION_UP
。为了使它起作用,您需要首先使用ACTION_DOWN
事件:if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_DOWN) { return true; }
。然后,您可以检查ACTION_UP
事件并执行操作(类似于以上答案)。如果您不使用该ACTION_DOWN
事件,则onEditorAction
不会被要求ACTION_UP
。
if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {...}
硬件键盘总是产生enter事件,但是软件键盘在singleLine EditTexts中返回不同的actionID和null。每次用户在已将此侦听器设置为的EditText中按下Enter键时,此代码都会响应,无论EditText或键盘类型如何。
import android.view.inputmethod.EditorInfo;
import android.view.KeyEvent;
import android.widget.TextView.OnEditorActionListener;
listener=new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
if (event==null) {
if (actionId==EditorInfo.IME_ACTION_DONE);
// Capture soft enters in a singleLine EditText that is the last EditText.
else if (actionId==EditorInfo.IME_ACTION_NEXT);
// Capture soft enters in other singleLine EditTexts
else return false; // Let system handle all other null KeyEvents
}
else if (actionId==EditorInfo.IME_NULL) {
// Capture most soft enters in multi-line EditTexts and all hard enters.
// They supply a zero actionId and a valid KeyEvent rather than
// a non-zero actionId and a null event like the previous cases.
if (event.getAction()==KeyEvent.ACTION_DOWN);
// We capture the event when key is first pressed.
else return true; // We consume the event when the key is released.
}
else return false;
// We let the system handle it when the listener
// is triggered by something that wasn't an enter.
// Code from this point on will execute whenever the user
// presses enter in an attached view, regardless of position,
// keyboard, or singleLine status.
if (view==multiLineEditText) multiLineEditText.setText("You pressed enter");
if (view==singleLineEditText) singleLineEditText.setText("You pressed next");
if (view==lastSingleLineEditText) lastSingleLineEditText.setText("You pressed done");
return true; // Consume the event
}
};
在singleLine = false中,Enter键的默认外观为弯曲的Enter键键盘。当最后一个EditText中的singleLine = true时,键显示DONE,而在它之前的EditTexts上显示NEXT。默认情况下,此行为在所有普通,Android和Google模拟器中都是一致的。scrollHorizontal属性没有任何区别。空测试很重要,因为电话对软输入的响应留给了制造商,甚至在仿真器中,香草的16级仿真器也对多行和scrollHorizontal EditTexts中的长软输入做出了响应,其actionId为NEXT,null为null。事件。
此页面确切描述了如何执行此操作。
https://developer.android.com/training/keyboard-input/style.html
设置android:imeOptions,然后您只需在onEditorAction中检查actionId即可。因此,如果将imeOptions设置为“ actionDone”,则将在onEditorAction中检查“ actionId == EditorInfo.IME_ACTION_DONE”。另外,请确保设置android:inputType。
这是上面链接的示例中的EditText:
<EditText
android:id="@+id/search"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="@string/search_hint"
android:inputType="text"
android:imeOptions="actionSend" />
您也可以使用setImeOptions(int)函数以编程方式进行设置。这是上面链接的示例中的OnEditorActionListener:
EditText editText = (EditText) findViewById(R.id.search);
editText.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
boolean handled = false;
if (actionId == EditorInfo.IME_ACTION_SEND) {
sendMessage();
handled = true;
}
return handled;
}
});
我知道这已经一岁了,但是我刚刚发现这对于EditText非常有效。
EditText textin = (EditText) findViewById(R.id.editText1);
textin.setInputType(InputType.TYPE_CLASS_TEXT);
它可以防止文本和空格以外的任何内容。我无法制表符,“返回”(“ \ n”)或其他任何内容。
就像Chad响应的附录(对我而言效果非常理想)一样,我发现我需要对KeyEvent操作类型进行检查,以防止我的代码执行两次(一次在键盘上按下,一次在键盘上按下一次)事件)。
if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_DOWN)
{
// your code here
}
有关重复动作事件(按住Enter键)的信息,请参见http://developer.android.com/reference/android/view/KeyEvent.html。
我有类似的目的。我想解决在扩展了TextView的AutoCompleteTextView中按下键盘上的“ Enter”键(我要自定义)的问题。我从上面尝试了不同的解决方案,它们似乎起作用了。但是,当我将我的设备(带有AOKP ROM的Nexus 4)上的输入类型从SwiftKey 3(工作正常)切换到标准Android键盘时,遇到了一些问题(在这里,不是处理来自侦听器的代码,而是在按下“ Enter”键后输入了它,我花了一些时间来解决这个问题,但是我不知道它在任何情况下都不管用,无论您使用哪种输入类型。
所以这是我的解决方案:
将xml中TextView的输入类型属性设置为“文本”:
android:inputType="text"
自定义键盘上“ Enter”键的标签:
myTextView.setImeActionLabel("Custom text", KeyEvent.KEYCODE_ENTER);
将一个OnEditorActionListener设置为TextView:
myTextView.setOnEditorActionListener(new OnEditorActionListener()
{
@Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event)
{
boolean handled = false;
if (event.getAction() == KeyEvent.KEYCODE_ENTER)
{
// Handle pressing "Enter" key here
handled = true;
}
return handled;
}
});
我希望这可以帮助其他人避免我遇到的问题,因为他们几乎使我发疯。
在您的xml中,将imeOptions属性添加到editText
<EditText
android:id="@+id/edittext_additem"
...
android:imeOptions="actionDone"
/>
然后,在Java代码中,将OnEditorActionListener添加到同一EditText
mAddItemEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if(actionId == EditorInfo.IME_ACTION_DONE){
//do stuff
return true;
}
return false;
}
});
这是解释-imeOptions = actionDone将为“ EnterKey”分配“ actionDone”。键盘中的EnterKey将从“ Enter”更改为“ Done”。因此,当按下Enter键时,它将触发此操作,因此您将对其进行处理。
您也可以做到。
editText.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event)
{
if (event.getAction() == KeyEvent.ACTION_DOWN
&& event.getKeyCode() == KeyEvent.KEYCODE_ENTER)
{
Log.i("event", "captured");
return false;
}
return false;
}
});
enter
编辑文本时,整个编辑文本会向下移动...如何解决此问题?
password.setOnEditorActionListener(new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if(event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
submit.performClick();
return true;
}
return false;
}
});
对我来说很好用
除了隐藏键盘
首先,您必须将EditText设置为监听按键
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set the EditText listens to key press
EditText edittextproductnumber = (EditText) findViewById(R.id.editTextproductnumber);
edittextproductnumber.setOnKeyListener(this);
}
其次,在按键时定义事件,例如,设置TextView文本的事件:
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
// Listen to "Enter" key press
if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER))
{
TextView textviewmessage = (TextView) findViewById(R.id.textViewmessage);
textviewmessage.setText("You hit 'Enter' key");
return true;
}
return false;
}
最后,不要忘记在顶部导入EditText,TextView,OnKeyListener,KeyEvent:
import android.view.KeyEvent;
import android.view.View.OnKeyListener;
import android.widget.EditText;
import android.widget.TextView;
完美地工作
public class MainActivity extends AppCompatActivity {
TextView t;
Button b;
EditText e;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button) findViewById(R.id.b);
e = (EditText) findViewById(R.id.e);
e.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (before == 0 && count == 1 && s.charAt(start) == '\n') {
b.performClick();
e.getText().replace(start, start + 1, ""); //remove the <enter>
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void afterTextChanged(Editable s) {}
});
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
b.setText("ok");
}
});
}
}
完美地工作
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId != 0 || event.getAction() == KeyEvent.ACTION_DOWN) {
// Action
return true;
} else {
return false;
}
}
});
Xml
<EditText
android:id="@+id/editText2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="@string/password"
android:imeOptions="actionGo|flagNoFullscreen"
android:inputType="textPassword"
android:maxLines="1" />
这应该工作
input.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {}
@Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
if( -1 != input.getText().toString().indexOf( "\n" ) ){
input.setText("Enter was pressed!");
}
}
});
在编辑器中键入此代码,以便它可以导入必要的模块。
query.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
if(actionId == EditorInfo.IME_ACTION_DONE
|| keyEvent.getAction() == KeyEvent.ACTION_DOWN
|| keyEvent.getAction() == KeyEvent.KEYCODE_ENTER) {
// Put your function here ---!
return true;
}
return false;
}
});
这是一个简单的静态函数,您可以将其放入您的Utils
或Keyboards
类中,当用户按下硬件或软件键盘上的返回键时,该类将执行代码。这是@earlcasper出色答案的修改版本
/**
* Return a TextView.OnEditorActionListener that will execute code when an enter is pressed on
* the keyboard.<br>
* <code>
* myTextView.setOnEditorActionListener(Keyboards.onEnterEditorActionListener(new Runnable()->{
* Toast.makeText(context,"Enter Pressed",Toast.LENGTH_SHORT).show();
* }));
* </code>
* @param doOnEnter A Runnable for what to do when the user hits enter
* @return the TextView.OnEditorActionListener
*/
public static TextView.OnEditorActionListener onEnterEditorActionListener(final Runnable doOnEnter){
return (__, actionId, event) -> {
if (event==null) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
// Capture soft enters in a singleLine EditText that is the last EditText.
doOnEnter.run();
return true;
} else if (actionId==EditorInfo.IME_ACTION_NEXT) {
// Capture soft enters in other singleLine EditTexts
doOnEnter.run();
return true;
} else {
return false; // Let system handle all other null KeyEvents
}
} else if (actionId==EditorInfo.IME_NULL) {
// Capture most soft enters in multi-line EditTexts and all hard enters.
// They supply a zero actionId and a valid KeyEvent rather than
// a non-zero actionId and a null event like the previous cases.
if (event.getAction()==KeyEvent.ACTION_DOWN) {
// We capture the event when key is first pressed.
return true;
} else {
doOnEnter.run();
return true; // We consume the event when the key is released.
}
} else {
// We let the system handle it when the listener
// is triggered by something that wasn't an enter.
return false;
}
};
}
final EditText edittext = (EditText) findViewById(R.id.edittext);
edittext.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// If the event is a key-down event on the "enter" button
if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER)) {
// Perform action on key press
Toast.makeText(HelloFormStuff.this, edittext.getText(), Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
});
响应EditText中<enter>的可靠方法是使用TextWatcher,LocalBroadcastManager和BroadcastReceiver。您需要添加v4支持库才能使用LocalBroadcastManager。我使用vogella.com上的教程:7.3“使用LocalBroadcastManager进行本地广播事件”,因为它具有完整的简洁代码示例。在onTextChanged中,before是更改 >;减去开始之前更改结束的索引。当在TextWatcher中时,UI线程正忙于更新editText的可编辑内容,因此当UI线程完成对editText的更新后,我们将发送一个Intent来唤醒BroadcastReceiver。
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.Editable;
//in onCreate:
editText.addTextChangedListener(new TextWatcher() {
public void onTextChanged
(CharSequence s, int start, int before, int count) {
//check if exactly one char was added and it was an <enter>
if (before==0 && count==1 && s.charAt(start)=='\n') {
Intent intent=new Intent("enter")
Integer startInteger=new Integer(start);
intent.putExtra("Start", startInteger.toString()); // Add data
mySendBroadcast(intent);
//in the BroadcastReceiver's onReceive:
int start=Integer.parseInt(intent.getStringExtra("Start"));
editText.getText().replace(start, start+1,""); //remove the <enter>
//respond to the <enter> here
android:inputType="textCapSentences"
),则回车会从输入中过滤掉,因此当用户按下Enter键时不会调用onTextChanged()。
Butterknife尚未回答此问题
布局XML
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/some_input_hint">
<android.support.design.widget.TextInputEditText
android:id="@+id/textinput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:imeOptions="actionSend"
android:inputType="text|textCapSentences|textAutoComplete|textAutoCorrect"/>
</android.support.design.widget.TextInputLayout>
JAVA APP
@OnEditorAction(R.id.textinput)
boolean onEditorAction(int actionId, KeyEvent key){
boolean handled = false;
if (actionId == EditorInfo.IME_ACTION_SEND || (key.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
//do whatever you want
handled = true;
}
return handled;
}
使用Kotlin,我制作了一个函数,用于处理EditText的各种“完成”式操作,包括键盘,并且可以修改它,也可以根据需要处理其他键:
private val DEFAULT_ACTIONS_TO_HANDLE_AS_DONE_FOR_EDIT_TEXT = arrayListOf(EditorInfo.IME_ACTION_SEND, EditorInfo.IME_ACTION_GO, EditorInfo.IME_ACTION_SEARCH, EditorInfo.IME_ACTION_DONE)
private val DEFAULT_KEYS_TO_HANDLE_AS_DONE_FOR_EDIT_TEXT = arrayListOf(KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_NUMPAD_ENTER)
fun EditText.setOnDoneListener(function: () -> Unit, onKeyListener: OnKeyListener? = null, onEditorActionListener: TextView.OnEditorActionListener? = null,
actionsToHandle: Collection<Int> = DEFAULT_ACTIONS_TO_HANDLE_AS_DONE_FOR_EDIT_TEXT,
keysToHandle: Collection<Int> = DEFAULT_KEYS_TO_HANDLE_AS_DONE_FOR_EDIT_TEXT) {
setOnEditorActionListener { v, actionId, event ->
if (onEditorActionListener?.onEditorAction(v, actionId, event) == true)
return@setOnEditorActionListener true
if (actionsToHandle.contains(actionId)) {
function.invoke()
return@setOnEditorActionListener true
}
return@setOnEditorActionListener false
}
setOnKeyListener { v, keyCode, event ->
if (onKeyListener?.onKey(v, keyCode, event) == true)
return@setOnKeyListener true
if (event.action == KeyEvent.ACTION_DOWN && keysToHandle.contains(keyCode)) {
function.invoke()
return@setOnKeyListener true
}
return@setOnKeyListener false
}
}
因此,示例用法:
editText.setOnDoneListener({
//do something
})
至于更改标签,我认为它取决于键盘应用程序,并且通常仅根据横向更改,如此处所述。无论如何,示例用法如下:
editText.imeOptions = EditorInfo.IME_ACTION_DONE
editText.setImeActionLabel("ASD", editText.imeOptions)
或者,如果要使用XML:
<EditText
android:id="@+id/editText" android:layout_width="wrap_content" android:layout_height="wrap_content"
android:imeActionLabel="ZZZ" android:imeOptions="actionDone" />
结果(以横向显示):
当用户按下返回键时,这将为您提供可调用的功能。
fun EditText.setLineBreakListener(onLineBreak: () -> Unit) {
val lineBreak = "\n"
doOnTextChanged { text, _, _, _ ->
val currentText = text.toString()
// Check if text contains a line break
if (currentText.contains(lineBreak)) {
// Uncommenting the lines below will remove the line break from the string
// and set the cursor back to the end of the line
// val cleanedString = currentText.replace(lineBreak, "")
// setText(cleanedString)
// setSelection(cleanedString.length)
onLineBreak()
}
}
}
用法
editText.setLineBreakListener {
doSomething()
}