我正在调用db helper的方法,同时用户按下done / next / enter,按钮但该代码执行两次,数据在表中输入两次。
以下是编辑文字的主要新闻事件:
editTextLitre.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
switch(keyCode){
case KeyEvent.KEYCODE_ENTER:
TextView txtlitres = (TextView)findViewById(R.id.edit_text_litre);
TextView totalamount = (TextView)findViewById(R.id.amount);
RadioButton rbBuffalo = (RadioButton) findViewById(R.id.radioBuffalo);
RadioButton rbCow = (RadioButton) findViewById(R.id.radioCow);
rbBuffalo.setText(Constants.Buffalo.toString());
rbCow.setText(Constants.Cow.toString());
radioanimal= (RadioGroup)findViewById(R.id.radioCategory);
int selectedid = radioanimal.getCheckedRadioButtonId();
rb = (RadioButton)findViewById(selectedid);
DBHelper dh=new DBHelper(getApplicationContext());
// TODO Auto-generated method stub
boolean save = dh.insertMilkDetails(mandali,rb.getText().toString(),totalamount.getText().toString(),txtlitres.getText().toString(),dt.toString(),session.toString());
if(save == true)
{
Toast.makeText(getApplicationContext(), "Details Saved Successfully", Toast.LENGTH_SHORT).show();
}
return false;
}
});
我无法理解为什么数据在数据库表中插入两次。
答案 0 :(得分:2)
非常简单,在按键期间为每个动作生成关键事件(即按键和按键)。您的代码会检查密钥代码类型,但不会验证该事件是ACTION_DOWN
还是ACTION_UP
。
传入的KeyEvent
对象为您提供此信息(see docs);你可能只想在up动作上插入。
使用EditText
后,另一个可能更好的选项是OnEditorActionListener
(docs),并不要求您检查此类内容。
答案 1 :(得分:0)
将您的代码更改为:
editTextLitre.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_ENTER:
TextView txtlitres = (TextView) findViewById(R.id.edit_text_litre);
TextView totalamount = (TextView) findViewById(R.id.amount);
RadioButton rbBuffalo = (RadioButton) findViewById(R.id.radioBuffalo);
RadioButton rbCow = (RadioButton) findViewById(R.id.radioCow);
rbBuffalo.setText(Constants.Buffalo.toString());
rbCow.setText(Constants.Cow.toString());
radioanimal = (RadioGroup) findViewById(R.id.radioCategory);
int selectedid = radioanimal.getCheckedRadioButtonId();
rb = (RadioButton) findViewById(selectedid);
DBHelper dh = new DBHelper(getApplicationContext());
// TODO Auto-generated method stub
boolean save = dh.insertMilkDetails(mandali, rb.getText().toString(), totalamount.getText().toString(), txtlitres.getText().toString(), dt.toString(), session.toString());
if (save == true) {
Toast.makeText(getApplicationContext(), "Details Saved Successfully", Toast.LENGTH_SHORT).show();
}
return false;
}
}
});
我改变了什么:if (event.getAction() == KeyEvent.ACTION_DOWN) { ...
因为当您按某个键时onKey
事件发生两次:一次按下时,一次释放按键时。