Saturday, March 29, 2014

Why editText1 the OnKey event is executed twice Toast? how to avoid


posts by ilove8 edited 2013-10-02 21:49:54

When editText1 nulls Enter, tips can not be empty, but why each prompt is displayed twice, track a bit, the onKey event is executed twice.
The 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 ("can not be empty");

bRet = true;
}
}
return bRet;
}
});


edit1Text text control below there is edit2Text
 
android: layout_width = "match_parent"
android: layout_height = "wrap_content">

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






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

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




Two tips on how to avoid? Thank you
<-! Main posts under Banner (D4) -><-! Posts under the main text (D5) ->
Reply:
click the Enter key once, KeyEvent.ACTION_DOWN and KeyEvent.ACTION_UP are triggered View.OnKeyListener (), so Toast display twice. You can put
 if (arg1 == KeyEvent.KEYCODE_ENTER) 
changed
 if (arg1 == KeyEvent.KEYCODE_ENTER && arg2.getAction () == KeyEvent.ACTION_DOWN) 
or
 if (arg1 == KeyEvent.KEYCODE_ENTER && arg2.getAction () == KeyEvent.ACTION_UP) < / pre> This will only show Toast at press ENTER or ENTER key release time. 
You can also be changed according to need, when pressed and released, Toast display different strings.

Reply:
 if (arg1 == KeyEvent.KEYCODE_ENTER && arg2.getAction () == KeyEvent.ACTION_UP) 

Effective, thank you ah
No. QQ how much you add you look.
Reply:
Results posted!!

No comments:

Post a Comment