如何使用Android Kotlin语言处理EditText上的Enter键?
答案 0 :(得分:16)
贝娄是上述问题最简单的解决方案
editText.setOnKeyListener(View.OnKeyListener { v, keyCode, event ->
if (keyCode == KeyEvent.KEYCODE_ENTER && event.action == KeyEvent.ACTION_UP) {
//Perform Code
return@OnKeyListener true
}
false
})
答案 1 :(得分:1)
我使用了何时表达来检查是否单击了输入按钮
edittext.setOnKeyListener { v, keyCode, event ->
when {
//Check if it is the Enter-Key, Check if the Enter Key was pressed down
((keyCode == KeyEvent.KEYCODE_ENTER) && (event.action == KeyEvent.ACTION_DOWN)) -> {
//perform an action here e.g. a send message button click
sendButton.performClick()
//return true
return@setOnKeyListener true
}
else -> false
}
}
答案 2 :(得分:0)
制作一个简单的扩展功能:
inline fun View.onKey(vararg events: Int, crossinline listener: (keyCode: Int) -> Boolean) {
setOnKeyListener { _, keyCode, event ->
if (event.action in events) listener(keyCode) else false
}
}
现在,您可以在需要的任何地方重用此功能,如下所示:
editText.onKey(KeyEvent.KEYCODE_ENTER, KeyEvent.ACTION_UP) {
// your reaction on action
true // return true if the listener has consumed the event, false otherwise.
}
答案 3 :(得分:0)
第1步!重要 在XML中指定两个属性:
static class universal
{
public static int a = 10;
}
class class_a
{
public void change1()
{
universal.a--;
}
}
class class_b
{
public void change2(ref int val)//use ref keyword for reference
{
int temp = val; //change in temp gives change in a
val -= 5;
}
}
static void Main(string[] args)
{
class_b B = new class_b();
class_a A = new class_a();
A.change1();
Console.WriteLine(universal.a);//it will print 9
B.change2(ref universal.a); //pass value by reference using ref keyword
Console.WriteLine(universal.a);//it will print 4
Console.ReadKey();
}
以便向用户显示正确的按下按钮guard let path = Bundle.main.path(forResource: "SwiftUI", ofType: "pdf") else { return }
let url = URL(fileURLWithPath: path)
以便告诉用户他必须输入哪些文本,对文本进行编号等步骤2 添加您的Kotlin文件:
android:imeOptions
此代码处理硬件和软件android:inputType
密钥。我选择yourEditText.setOnEditorActionListener { _, keyCode, event ->
if (((event?.action ?: -1) == KeyEvent.ACTION_DOWN)
|| keyCode == EditorInfo.IME_PUT_THE_ACTION_YOU_HAVE_SET_UP_IN_STEP_1) {
// Your code here
return@setOnEditorActionListener true
}
return@setOnEditorActionListener false
}
的原因是因为它可以更好地处理此操作。根据Docs:
enter