Android EditText 点击 imeOption

3
使用按钮很简单,
<Button 
    android:blablabla="blabla"
    ...
    android:onClick="doSomething" />

这将执行doSomething(View)函数。

我们如何使用EditText模拟这个功能? 我已经阅读了相关内容,大多数人使用imeOptions(仍然似乎是必要的),然后在EditText对象上实现actionListener。

这就是我迷失的地方。 是否有一种方法可以将键盘上的“完成”操作(或发送或...)实现为像按钮一样的onClick函数,还是我们需要显式实现监听器?

谢谢!


如果我的回答对您有帮助,或者根据您的问题是正确的,请考虑接受它,@MrMeThumbsUp :) - undefined
3个回答

6
下面的代码将在您按下软键盘中的“完成”键时执行某些操作。
editText.setOnEditorActionListener(new OnEditorActionListener() {        
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if(actionId==EditorInfo.IME_ACTION_DONE){
            //do your actions here that you like to perform when done is pressed
            //Its advised to check for empty edit text and other related 
            //conditions before preforming required actions
        }
    return false;
    }
});

希望这能帮到你!

抱歉,但这不是我要问的。我知道如何使用监听器实现它。我想知道是否有一种方法可以在XML中添加一些代码来定义按下“完成”按钮后应执行哪个函数。就像我们使用android:onClick="dosomething"为按钮实现一样。我们也不会在该按钮上实现onClick监听器,而是定义要执行的函数。 - MrMe TumbsUp
@MrMeTumbsUp 你应该接受这个答案,因为这是检测 IME 上单个按钮点击的唯一方法。 - IgorGanapolsky

1
我假设你想在单击EditText时运行一些代码?如果是这样,我在网站的另一个线程中找到了一个解决方案:
    EditText myEditText = (EditText) findViewById(R.id.myEditText);
    myEditText.setOnFocusChangeListener(new OnFocusChangeListener() {

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {

    then do this code here

    }
}
});

通过:EditText字段的更好的OnClick方法?


不,我想在用户按下“完成”或您选择的任何imeOption时运行一些代码。我知道这可以通过监听器完成,但我的问题是是否可以像按钮一样定义xml文件中函数的名称。 android:onClick =“doSomething” - MrMe TumbsUp

0

Kotlin 版本

editText.setOnEditorActionListener { view, actionId, event -> 
    if(actionId==EditorInfo.IME_ACTION_DONE){
        // do your actions here that you like to perform when done is pressed
        true // return true from your lambda when the action is treated
    }
    false // return false from your lambda when the action is not treated
}

Java 版本

editText.setOnEditorActionListener(new OnEditorActionListener() {        
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if(actionId==EditorInfo.IME_ACTION_DONE){
            //do your actions here that you like to perform when done is pressed
            return true; // return true when the action is treated
        }
        return false; // return false when the action is not treated
    }
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接