更新EditText时出错

时间:2013-05-10 09:41:27

标签: android android-layout android-intent android-listview

在某些设备上,使用此代码,在插入要在EditText from_quantity中转换的值期间,EditText to_quantity不会实时更新。可能是什么问题?

编辑文本from_quantity:

from_quantity.setOnKeyListener(new OnKeyListener(){

    public boolean onKey(View v, int keyCode, KeyEvent event){

        try{
        if(!(Double.isNaN(Double.valueOf(from_quantity.getText().toString())))){
                                                  convert(from_quantity.getText().toString(), "to");
        }
        }catch(NumberFormatException e){
            Log.d("error", e.toString());
        }
            return false;
        }
        });

            from_quantity.setOnTouchListener(new OnTouchListener(){

                            public boolean onTouch(View v, MotionEvent event) {
                                    //Clear Quantities
                                    from_quantity.setText("");
                                    to_quantity.setText("");
                                    return false;
                            }

            });

编辑文字to_quantity:

to_quantity.setOnKeyListener(new OnKeyListener() {
     public boolean onKey(View v, int keyCode, KeyEvent event) {
         try{
            if(!(Double.isNaN(Double.valueOf(to_quantity.getText().toString())))) {
                  convert(to_quantity.getText().toString(), "from");
            }
          } catch(NumberFormatException e) {
               Log.d("error", e.toString());
          }
          return false;
     }
});


to_quantity.setOnTouchListener(new OnTouchListener(){
      public boolean onTouch(View v, MotionEvent event) {
          //Clear Quantities
          from_quantity.setText("");
          to_quantity.setText("");
          return false;
      }

});

3 个答案:

答案 0 :(得分:0)

如果使用设备的软键盘,则不会调用OnKeyListener。你应该使用TextWatcher。

onKeyListener not working with soft keyboard (Android)

答案 1 :(得分:0)

某些软件键盘不会启动onKey()事件。创建TextWatcher并将其设置为EditText的监听器:

to_quantity.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        String text = s.toString() ;
        try{
            if(!(Double.isNaN(Double.valueOf(text)))) {
                convert(text, "from");
            }
        } catch(NumberFormatException e) {
            Log.d("error", e.toString());
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
            int after) {
        // TODO Auto-generated method stub

    }

    @Override
    public void afterTextChanged(Editable s) {
        // TODO Auto-generated method stub

    }
});

答案 2 :(得分:0)

如果您想使用软键盘,则需要将setFocusable设置为目标视图:

setFocusableInTouchMode(true); //Enable soft keyboard on touch for target view

setFocusable(true); //Enable hard keyboard to target view