我的场景如下:我有一个搜索 fragment ,在那个 fragment 中,我有 3 个文本字段(按名称、邮政编码和距离搜索)。当焦点应用于“按名称搜索”字段时,其他 2 个字段消失并且所选字段的宽度增加。我的问题是我不能失去对第一个字段的关注,所以在我写完信息后,我不能使用其他 2 个字段。
我正在寻找一种方法,当我按下“enter”或当我按下屏幕上除文本字段以外的任何其他地方时,可以使字段失去焦点。
这是我现在正在运行的代码:
final EditText searchByName = (EditText) getActivity().findViewById(R.id.search_by_name);
final EditText searchByZipcode = (EditText) getActivity().findViewById(R.id.search_by_zipcode);
final EditText searchByDistance = (EditText) getActivity().findViewById(R.id.search_by_distance);
searchByName.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
/* When focus is lost check that the text field
* has valid values.
*/
if (hasFocus) {
searchByName.getLayoutParams().width=900;
searchByZipcode.setVisibility(View.INVISIBLE);
searchByDistance.setVisibility(View.INVISIBLE);
} else {
searchByName.getLayoutParams().width=405;
searchByZipcode.setVisibility(View.VISIBLE);
searchByDistance.setVisibility(View.VISIBLE);
}
}
});
searchByZipcode.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
/* When focus is lost check that the text field
* has valid values.
*/
if (hasFocus) {
searchByZipcode.getLayoutParams().width=700;
searchByName.setVisibility(View.INVISIBLE);
} else {
searchByZipcode.getLayoutParams().width=240;
searchByName.setVisibility(View.VISIBLE);
}
}
});
最佳答案
在您的 Activity 类中,添加下面的方法,它会为您工作。它将隐藏键盘并清除您单击它会起作用的外部任何地方的焦点。
@Override
public boolean onTouchEvent(MotionEvent event) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.
INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
return true;
}
关于android - 当我按回车键或屏幕上的其他任何地方时,如何失去对文本字段的关注?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48706834/