2013年10月8日星期二

[Android] The OnKey event editText1 Why executed twice Toast? how to avoid

 This post last edited by the ilove8 on 2013-10-02 21:49:54

When editText1 nulls Enter key , suggesting not be empty, but why each displayed twice tips , track a bit, the onKey event executed twice.
main code is as follows

editText1.setOnKeyListener(new View.OnKeyListener() {
  @Override
  public boolean onKey(View arg0, int arg1, KeyEvent arg2) {
    boolean bRet = false;
    String s = editText1.getText().toString();
    if(arg1==KeyEvent.KEYCODE_ENTER){
      if(s.length() == 0){
        ShowToast("不能为空");
        
        bRet = true;
      }
    }
  return bRet;
}        
});


edit1Text text controls below there is a edit2Text

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <EditText
            android:id="@+id/editText1"
            android:layout_width="0dip"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:singleLine="true"
            android:ems="10" >

            <requestFocus />
        </EditText>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <EditText
            android:id="@+id/editText2"
            android:layout_width="0dip"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:singleLine="true"
            android:ems="10" />

    </LinearLayout>


How to avoid prompted twice ? Thank
------ Solution ----------------------------- ---------------
click once on the Enter key , KeyEvent.ACTION_DOWN and KeyEvent.ACTION_UP are triggered View.OnKeyListener (), so Toast displayed twice. You can put
if(arg1==KeyEvent.KEYCODE_ENTER)
change
if(arg1==KeyEvent.KEYCODE_ENTER && arg2.getAction() == KeyEvent.ACTION_DOWN)
or
if(arg1==KeyEvent.KEYCODE_ENTER && arg2.getAction() == KeyEvent.ACTION_UP)
This will only press the ENTER key or release the ENTER key when the display Toast.
You may also need to be changed when press and release , Toast display different string.

------ eference ------------------------------------ ---
if(arg1==KeyEvent.KEYCODE_ENTER && arg2.getAction() == KeyEvent.ACTION_UP)

effective, thank you ah
plus you QQ, how much you look .
------ eference ---------------------------- -----------
Results posted !!

没有评论:

发表评论