当我从软键盘输入时,我想触发搜索,但它不起作用。如果在物理键盘上按下键输入(通过模拟器),它可以正常工作。也许我是错误的倾听者?
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)
答案 0 :(得分:0)
尝试将以下代码添加到R.id.search_view
:
android:imeOptions="actionSearch"
android:inputType="text"