【问题标题】:How to Trigger a Button when Enter is Pressed in Android?在Android中按下Enter时如何触发按钮?
【发布时间】:2015-04-28 20:49:37
【问题描述】:

我有一个按钮,当我在 EditText 中键入一些数字时,它会做很多事情。我想知道如何通过简单地按下“Enter”键来触发这个按钮。 目前我只有一个 onClickListener,用户在将数据输入到 EditText 后必须按下它。我希望 Button 保留在那里,并为用户提供进一步的选项。

有人可以帮忙吗? 下面的代码什么都不做。当我在键盘上按 Enter 时,它只是转到下一行...

EditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)){
                    Button.performClick();

                }
                return false;
            }
        });

【问题讨论】:

标签: android


【解决方案1】:

此代码适用于我

youredittext.setOnEditorActionListener(new 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");
        }    
        return false;
    }
});

【讨论】:

    【解决方案2】:

    看到这个:

         edittext.setOnKeyListener(new OnKeyListener(){
        public boolean onKey(View v, int keyCode, KeyEvent event) {     
                if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) 
                {
                   Toast.makeText(MainActivity.this,edittext.getText(), Toast.LENGTH_LONG).show();
                   return true;
                }
    

    【讨论】:

      【解决方案3】:

      请参考以下代码以获取您的解决方案,

      editText.setOnEditorActionListener(new TextView.OnEditorActionListener()
          {
              @Override
              public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent)
              {
                  if (id == EditorInfo.IME_NULL)
                  {
                     //Do your button action here 
      
                      return true;
                  }
                  return false;
              }
          });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-10-08
        • 2011-02-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-01
        • 1970-01-01
        相关资源
        最近更新 更多