我是 Android 新手。我正在尝试创建一个文本框,然后按完成键,它应该将值传递给java代码。为此,我使用 setOnEditorActionListener 。我搜索了如何执行此操作并获得了许多有关如何实现它的答案。示例:
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;
}
});
我想问一下这个东西应该写在哪里?用什么方法?我尝试在 onCreate 中执行此操作,但它引发了一些错误。我以某种方式使用此代码使其工作:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.unlock);
Log.i(TAG, "onCreate");
editText= (EditText) findViewById(R.id.editText);
editText.setOnEditorActionListener(this);
}
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
boolean handled = false;
if (actionId == EditorInfo.IME_ACTION_SEND) {
Log.i(TAG, "button pressed");
Toast.makeText(this, "Hey you just clicked the DONE button", Toast.LENGTH_SHORT).show();
handled = true;
}
return handled;
}
这里我使用了this关键字,但我不明白为什么要使用它。 问题1.请帮我理解,为什么我们使用这个关键字..
问题 2. 为什么下面的代码不起作用?
public void checkInput() {
Log.i(TAG, "Enter checkInput method");
final EditText editText= (EditText) findViewById(R.id.editText);
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
Log.i(TAG, "Enter onEditorAction");
boolean handled = false;
if (actionId == EditorInfo.IME_ACTION_SEND) {
Log.i(TAG, "button pressed")
handled = true;
}
return handled;
}
});
}
我从 onCreate 调用了这个 checkInput 方法。
最佳答案
回答问题 1:
Here I used this keyword, and I don't understand why have I used it. Question 1. Please help me understand, why have we used this keyword..
您告诉 Java 查看 Activity 类以实现 TextView.OnEditorActionListener
接口(interface)所需的方法。因此,对于与软键盘的所有交互,Java 都会在您的类中查找方法:onEditorAction
为了使上述工作正常,您的 Activity 需要定义如下:
公共(public)类 MyActivity 实现 TextView.OnEditorActionListener {}
对于问题 2:
Question 2. Why wasn't it working in the below code?
要检查“完成”操作,您的 if
语句应为:
if (actionId == EditorInfo.IME_ACTION_DONE) { ... }
希望有帮助。
关于java - 如何处理 Android 键盘操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35950973/