在片段类中,我将此代码放在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;
}
答案 0 :(得分:0)
同样的问题发生在我身上,我发现为edittext设置ontough listener解决了这个问题。这是代码。
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;
}
答案 1 :(得分:0)
onKey功能仅检测硬件密钥,而不是软密钥。对于屏幕键盘,您需要实现TextWatcher。