【问题标题】:EditText is not detecting keysEditText 没有检测到键
【发布时间】:2014-08-18 23:28:58
【问题描述】:

在片段类中,我将此代码放在 onCreateView 中以监视用户是否按下 ENTER,但它不起作用,甚至没有捕获任何其他键盘按下。 N.B.:我正在虚拟模拟器上进行测试。

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
    {
        View rootView = inflater.inflate(R.layout.fragment_sub, container, false);


        EditText addProduct = (EditText)rootView.findViewById(R.id.editText1);
        addProduct.setOnKeyListener(new OnKeyListener() {

            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                Log.i("any button","button");
                // if keydown and "enter" is pressed
                if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                    ((EditText)v).setText("");
                    Log.i("here","im here");
                    return true;

                } else if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_9)) {

                    ((EditText)v).setText("");
                    Log.i("or here","9");
                    return true;
                }
                //do your stuff here against pressing shift key

                return false;
            }
        });
        return rootView;
        }

【问题讨论】:

    标签: android android-edittext enter


    【解决方案1】:

    onKey 函数只检测硬件键,不检测软键。对于屏幕键盘,您需要实现 TextWatcher。

    【讨论】:

      【解决方案2】:

      我也遇到了同样的问题,我发现为 edittext 设置严格的侦听器可以解决问题。这是代码。

      name=(EditText)findViewById(R.id.editText1);
      name.setOnTouchListener(this);
      
      @Override
      public boolean onTouch(View arg0, MotionEvent arg1) {
          // TODO Auto-generated method stub
          arg0.requestFocusFromTouch();
          InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
          imm.showSoftInput(arg0, InputMethodManager.SHOW_IMPLICIT);
          return true;
      }
      

      【讨论】:

      • 我会说,先设置ontough listener,然后设置key listener。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-07
      • 2017-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多