我想在虚拟键盘上单击回车键后显示 Toast 消息



请在下面找到更新的代码。

以下是代码:

package com.Wase.edittext;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.EditText;
import android.widget.Toast;
import com.Wase.edittext.R;
import android.widget.TextView;
public class MyAndroidAppActivity extends Activity {
 private EditText edittext;
 private EditText edittext1;
 @Override
 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my_android_app);
    addKeyListener();
 edittext.requestFocus();
}

 public void addKeyListener() {
    // get edittext component
    edittext = (EditText) findViewById(R.id.editText);
    edittext1 = (EditText) findViewById(R.id.editText1);

    // add a keylistener to keep track user input
    edittext.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int keyCode, KeyEvent event) {
    // if keydown and "enter" is pressed
    if ((event.getAction() == KeyEvent.ACTION_DOWN)
        && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER))
    {
        edittext1.requestFocus();
    }
    edittext1.setOnEditorActionListener(new TextView.OnEditorActionListener() {
         @Override
         public boolean onEditorAction(TextView a, int b, KeyEvent c) {
    // if keydown and "enter" is pressed
    if ((c.getAction() == KeyEvent.ACTION_DOWN)
        && (c.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
        //hide the keyboard
        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(edittext.getWindowToken(), 0);
                imm.hideSoftInputFromWindow(edittext1.getWindowToken(), 0);
    // display a floating message
        Toast.makeText(MyAndroidAppActivity.this,
            edittext.getText() + " " + edittext1.getText(), Toast.LENGTH_SHORT).show();
        return true;
    }
        return false;
}
 });
        return false;
}
    });
 }
}

此代码仅用于键盘单击或系统键盘单击。我想隐藏虚拟键盘并在单击android虚拟键盘的回车键时显示Toast消息。

请帮我解决这个问题。

每次在编辑文本中按下键时,您都会设置一个新的onKeyListener来编辑文本1...这真的是你想做的吗?

按下

回车键时必须检测的代码似乎很好。您将需要添加以下代码来关闭键盘并执行 Toast。

editText.setOnEditorActionListener(new TextView.OnEditorActionListener(){
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if ((event.getAction() == KeyEvent.ACTION_DOWN)
                && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER))
            {
                InputMethodManager imm = (InputMethodManager)getSystemService(
                    Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);
                Toast.makeText(MyAndroidAppActivity.this, "My message", Toast.LENGTH_SHORT).show();
            }
       }
}

相关内容

  • 没有找到相关文章

最新更新