我想在按下软键盘上的回车键时触发搜索,但是它不起作用。如果在物理键盘上通过仿真器按了Enter键,则可以正常工作。也许我听错了声音?
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
readJson();
final View view= inflater.inflate(R.layout.fragment_main, container, false);
EditText search = (EditText) view.findViewById(R.id.search_view);
search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH ||
actionId == EditorInfo.IME_ACTION_DONE ||
actionId == EditorInfo.IME_ACTION_GO ||
event.getAction() == KeyEvent.ACTION_DOWN &&
event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
if (!event.isShiftPressed()) {
int found=0;
String inserted = v.getText().toString();
for(int i=0;i<city_list.size();i++){
if(inserted.equalsIgnoreCase(city_list.get(i).get("name").toString())){
found=1;
TextView id = (TextView) view.findViewById(R.id.city_id);
id.setText(city_list.get(i).get("id").toString());
TextView lat = (TextView) view.findViewById(R.id.city_lat);
lat.setText(city_list.get(i).get("lat").toString());
TextView lon = (TextView) view.findViewById(R.id.city_long);
lon.setText(city_list.get(i).get("lon").toString());
}
}
if(found==0) {
Toast.makeText(getContext(), "City not found", Toast.LENGTH_SHORT).show();
}
InputMethodManager inputManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
return true; // consume.
}
}
return false; // pass on to other listeners.
}
});
也尝试过:
search.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN &&
keyCode == KeyEvent.KEYCODE_ENTER)
最佳答案
尝试将以下代码添加到您的R.id.search_view
中:
android:imeOptions="actionSearch"
android:inputType="text"
关于java - 按下软键盘上的Enter键不会触发事件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42346832/