有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java提交一个AlertDialog。在安卓 studio中,通过按键盘上的enter键来包含编辑文本的生成器

这是我的AlertDialog代码。具有带有EditText的自定义视图的生成器。在EditText中输入值后,我希望键盘上的Enter键的操作方式与AlertDialog的PositiveButton相同。建设者我已经在XML文件中包含了必要的“imeOptions”部分。我在按Enter键时成功地执行了代码,但AlertDialog没有执行。生成器仍在屏幕上,不会像AlertDialog上的PositiveButton一样关闭。单击生成器

    //AlertDialog to set weekly income
    incomeAlert = new AlertDialog.Builder(this);
    incomeInflater = this.getLayoutInflater();
    incomeDialogView = incomeInflater.inflate(R.layout.activity_weekincome, null);
    incomeAlert.setView(incomeDialogView);
    et_WeekIncome = incomeDialogView.findViewById(R.id.ls_WeekIncome);
    et_WeekIncome.setOnEditorActionListener(new EditText.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                submitIncome();
                return true;
            }
            return false;
        }
    });
    incomeAlert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            submitIncome();
        }
    });

提前感谢您的帮助

更新:我成功地关闭了AlertDialog。通过添加另一段代码构建器,如下所示

        AlertDialog incomeDialog = incomeAlert.create();
        incomeDialog.show();

然后,当需要解雇时,我使用

        incomeDialog.dismiss();

因为Dismise()不适用于AlertDialog。生成器,我必须通过AlertDialog创建生成器。然后我在AlertDialog上调用disclesh()

谢谢大家的意见


共 (3) 个答案

  1. # 1 楼答案

    Since dismiss() is not available with AlertDialog.Builder, I had to create the Builder through an AlertDialog. Then I call dismiss() on the AlertDialog.

    还有另一种解决此问题的方法:使用SetOnSwowListener回调来设置密钥侦听器。这使您可以访问对话框的disclose()方法

    incomeAlert.setOnShowListener((DialogInterface d) -> {
        et_WeekIncome.setOnKeyListener((v, keyCode, event) -> {
            if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_ENTER) {
                onClick(dialog, BUTTON_POSITIVE);
                d.dismiss();
                return true;
            }
            return false;
        });
    
  2. # 2 楼答案

    您可以在编辑文本中使用OnKeyListener来处理特定的按键

    mEditTV.setOnKeyListener(new View.OnKeyListener() {
    
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_ENTER) {
                // do action
                return true;
            }
            return false;
        }
    });
    
  3. # 3 楼答案

    您可以通过这种方式使用上面的setOnKeyListener

    et_WeekIncome.setOnKeyListener(new OnKeyListener(){
    public boolean onKey(View v, int keyCode, KeyEvent event)
    {
        if (event.getAction() == KeyEvent.ACTION_DOWN)
        {
            switch (keyCode)
            {
              case KeyEvent.KEYCODE_ENTER:
                submitIncome();
                return true;
    
              default:
                break;
            }
          }return false;
         }
    });