【问题标题】:Android Use Done button on Keyboard to click buttonAndroid 使用键盘上的完成按钮单击按钮
【发布时间】:2012-03-07 04:50:41
【问题描述】:

好的,在我的应用程序中,我有一个字段供用户输入数字。我将该字段设置为仅接受数字。当用户单击该字段时,它会弹出键盘。在键盘上(在 ICS 上)有一个完成按钮。我希望键盘上的完成按钮触发我的应用程序中的提交按钮。我的代码如下。

package com.michaelpeerman.probability;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Random;

public class ProbabilityActivity extends Activity implements OnClickListener {

private Button submit;
ProgressDialog dialog;
int increment;
Thread background;
int heads = 0;
int tails = 0;

public void onCreate(Bundle paramBundle) {
    super.onCreate(paramBundle);
    setContentView(R.layout.main);
    submit = ((Button) findViewById(R.id.submit));
    submit.setOnClickListener(this);
}

public void onClick(View view) {
    increment = 1;
    dialog = new ProgressDialog(this);
    dialog.setCancelable(true);
    dialog.setMessage("Flipping Coin...");
    dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    dialog.setProgress(0);
    EditText max = (EditText) findViewById(R.id.number);
    int maximum = Integer.parseInt(max.getText().toString());
    dialog.setMax(maximum);
    dialog.show();
    dialog.setOnCancelListener(new OnCancelListener(){

          public void onCancel(DialogInterface dialog) {

              background.interrupt();
              TextView result = (TextView) findViewById(R.id.result);
                result.setText("heads : " + heads + "\ntails : " + tails);


          }});


    background = new Thread(new Runnable() {
        public void run() {
            heads=0;
            tails=0;
            for (int j = 0; !Thread.interrupted() && j < dialog.getMax(); j++) {
                int i = 1 + new Random().nextInt(2);
                if (i == 1)
                    heads++;
                if (i == 2)
                    tails++;
                progressHandler.sendMessage(progressHandler.obtainMessage());
            }
        }
    });
    background.start();
}

Handler progressHandler = new Handler() {
    public void handleMessage(Message msg) {

        dialog.incrementProgressBy(increment);
        if (dialog.getProgress() == dialog.getMax()) {
            dialog.dismiss();
            TextView result = (TextView) findViewById(R.id.result);
            result.setText("heads : " + heads + "\ntails : " + tails);


        }
    }

};

}

【问题讨论】:

标签: android keyboard-events android-softkeyboard


【解决方案1】:

你也可以使用这个(设置在 EditText 上执行操作时调用的特殊侦听器),它适用于 DONE 和 RETURN:

max.setOnEditorActionListener(new OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) {
                Log.i(TAG,"Enter pressed");
            }    
            return false;
        }
    });

【讨论】:

  • 我怎样才能设置它来触发点击我已经运行提交按钮 public void onClick(View view) {
  • 您可以将所有代码移动到单个函数中然后调用它或使用performClick()
  • 点击完成按钮时这对我不起作用,KeyEvent 始终为空。但是 actionId 设置为 EditorInfo.IME_ACTION_DONE 而我可以使用它。 (这是在 android 4.2.2 中,此时甚至与 android sdk 文档不匹配)
【解决方案2】:

你可以试试IME_ACTION_DONE

此操作执行“完成”操作,无需输入任何内容,并且 IME 将被关闭。

 Your_EditTextObj.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                boolean handled = false;
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                  /* Write your logic here that will be executed when user taps next button */


                    handled = true;
                }
                return handled;
            }
        });

【讨论】:

  • 这一款非常适合我。小心返回 TRUE。键盘仍然显示。如果你想隐藏键盘返回 FALSE。
  • 像宝石一样工作!
【解决方案3】:

Kotlin 解决方案

在 Kotlin 中处理 done 动作的基本方法是:

edittext.setOnEditorActionListener { _, actionId, _ ->
    if (actionId == EditorInfo.IME_ACTION_DONE) {
        // Call your code here
        true
    }
    false
}

Kotlin 扩展

使用它在您的主代码中调用edittext.onDone {/*action*/}。使其更具可读性和可维护性

edittext.onDone { submitForm() }

fun EditText.onDone(callback: () -> Unit) {
    setOnEditorActionListener { _, actionId, _ ->
        if (actionId == EditorInfo.IME_ACTION_DONE) {
            callback.invoke()
            true
        }
        false
    }
}

不要忘记将这些选项添加到您的编辑文本中

<EditText ...
    android:imeOptions="actionDone"
    android:inputType="text"/>

如果您需要inputType="textMultiLine"支持,read this post

【讨论】:

  • 这个监听器实际上总是返回false(Kotlin 益智游戏;)),但这很好:我们通常希望键盘关闭。
  • @gmk57 尝试在 if 语句中添加 else 并让它包含 false。我相信您总是看到错误,因为 if 语句设置为 true,但随后它直接流向下一行(在 if 之外)的 false。
【解决方案4】:

试试这个:

max.setOnKeyListener(new OnKeyListener(){
    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event){
        if(keyCode == event.KEYCODE_ENTER){
            //do what you want
        }
    }
});

【讨论】:

  • 当您按下任何按钮时,您的视图会生成事件 onKey,并且当 keyCode 与右键匹配时,它会执行您想要的操作
  • 按钮必须有焦点
【解决方案5】:

在 Xamarin.Android(跨平台)上试试这个

edittext.EditorAction += (object sender, TextView.EditorActionEventArgs e) {
       if (e.ActionId.Equals (global::Android.Views.InputMethods.ImeAction.Done)) {
           //TODO Something
       }
};

【讨论】:

    【解决方案6】:

    当您创建 LoginActivity 时,我从 AndroidStudio 复制了以下代码。 我使用ime属性

    在你的布局中

    <EditText android:id="@+id/unidades" android:layout_width="match_parent"
                        android:layout_height="wrap_content" android:hint="@string/prompt_unidades"
                        android:inputType="number" android:maxLines="1"
                        android:singleLine="true"
                        android:textAppearance="?android:textAppearanceSmall"
                        android:enabled="true" android:focusable="true"
                        android:gravity="right"
                        android:imeActionId="@+id/cantidad"
                        android:imeActionLabel="@string/add"
                        android:imeOptions="actionUnspecified"/>
    

    在你的活动中

    editTextUnidades.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == R.id.cantidad || actionId == EditorInfo.IME_NULL) {
                    addDetalle(null);
                    return true;
                }
                return false;
            }
        });
    

    【讨论】:

      【解决方案7】:

      您可以在关键监听器上实现:

      public class ProbabilityActivity extends Activity implements OnClickListener, View.OnKeyListener {
      

      在 onCreate 中:

      max.setOnKeyListener(this);
      

      ...

      @Override
      public boolean onKey(View v, int keyCode, KeyEvent event){
          if(keyCode == event.KEYCODE_ENTER){
              //call your button method here
          }
          return true;
      }
      

      【讨论】:

        【解决方案8】:

        如果您想通过单击按钮等任何事件来捕捉键盘输入按钮来完成您想要完成的工作,您可以为该文本视图编写以下简单代码

        Edittext ed= (EditText) findViewById(R.id.edit_text);
        
        ed.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                // Do you job here which you want to done through event
            }
            return false;
        }
        });
        

        【讨论】:

          【解决方案9】:

          Kotlin 和数字键盘

          如果您使用的是数字键盘,则必须关闭键盘, 它会是这样的:

          editText.setOnEditorActionListener { v, actionId, event ->
            if (action == EditorInfo.IME_ACTION_DONE || action == EditorInfo.IME_ACTION_NEXT || action == EditorInfo.IME_ACTION_UNSPECIFIED) {
                //hide the keyboard
                val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                imm.hideSoftInputFromWindow(windowToken, 0)
                //Take action
                editValue.clearFocus()
                return true
            } else {
                return false
            }
          }
          

          【讨论】:

            【解决方案10】:

            在你的布局中使用这个类:

            public class ActionEditText extends EditText
            {
                public ActionEditText(Context context)
                {
                    super(context);
                }
            
                public ActionEditText(Context context, AttributeSet attrs)
                {
                    super(context, attrs);
                }
            
                public ActionEditText(Context context, AttributeSet attrs, int defStyle)
                {
                    super(context, attrs, defStyle);
                }
            
                @Override
                public InputConnection onCreateInputConnection(EditorInfo outAttrs)
                {
                    InputConnection conn = super.onCreateInputConnection(outAttrs);
                    outAttrs.imeOptions &= ~EditorInfo.IME_FLAG_NO_ENTER_ACTION;
                    return conn;
                }
            

            }

            在xml中:

            <com.test.custom.ActionEditText
                            android:id="@+id/postED"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_weight="1"
                            android:background="@android:color/transparent"
                            android:gravity="top|left"
                            android:hint="@string/msg_type_message_here"
                            android:imeOptions="actionSend"
                            android:inputType="textMultiLine"
                            android:maxLines="5"
                            android:padding="5dip"
                            android:scrollbarAlwaysDrawVerticalTrack="true"
                            android:textColor="@color/white"
                            android:textSize="20sp" />
            

            【讨论】:

              【解决方案11】:
              max.setOnKeyListener(new OnKeyListener(){
                @Override
                public boolean onKey(View v, int keyCode, KeyEvent event){
                  if(keyCode == event.KEYCODE_ENTER){
                      //do what you want
                  }
                }
              });
              

              【讨论】:

              • 对您的代码进行注释总能提高答案的可读性...
              • 虽然此代码可能会回答问题,但提供额外的context 关于它如何和/或为什么解决问题将提高答案的长期价值。请记住,您正在为将来的读者回答问题,而不仅仅是现在提问的人!请edit您的答案添加解释,并说明适用的限制和假设。提及为什么这个答案比其他答案更合适也没有什么坏处。
              【解决方案12】:

              你的 Last Edittext .setOnEditorActionListener 调用这个方法自动命中api

              我在 et_password 的 LoginActivity 中被调用

               et_Pass.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                          public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                              if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) {
              
                                  Log.i(TAG,"Enter pressed");
                                  Log.i(Check Internet," and Connect To Server");
              
                              }
                              return false;
                          }
                      });
              

              工作正常

              【讨论】:

                【解决方案13】:

                这是一个 Kotlin 版本:

                editText.setOnEditorActionListener { v, actionId, event ->
                  if(actionId == EditorInfo.IME_ACTION_DONE){
                      //Put your action there
                      true
                  } else {
                      false
                  }
                }
                

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 2015-04-06
                  • 2011-03-21
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2012-11-15
                  • 2011-06-25
                  相关资源
                  最近更新 更多