簡體   English   中英

在Android中按下Enter鍵時如何觸發按鈕?

[英]How to Trigger a Button when Enter is Pressed in Android?

我有一個Button,當我在EditText中鍵入一些數字時,它將完成很多工作。我想知道如何通過簡單地按“ Enter”鍵來觸發此Button。 現在我只有一個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;
            }
        });

該代碼對我有用

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;
    }
});

看到這個:

     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;
            }

請參考以下代碼以獲取解決方案,

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;
        }
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM