android - 当我按回车键或屏幕上的其他任何地方时,如何失去对文本字段的关注?

标签 android

我的场景如下:我有一个搜索 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/

相关文章:

android - Delphi Android密码保护一个文件

android - DateFormat.getDateTimeInstance 在 android 5 中使用错误的本地时间格式

android - 自定义 ListView 条目在 JB 中有效,在 Gingerbread 中无效

java - 是否可以在 Android Pepper Robot 模拟器中测试讨论操作

android - Android 上的 OAuth + Twitter : Callback fails

java - 在数组之前用 2 个对象解析 JSON

android - 以编程方式更改蓝牙音量?

java - 如何从 Firebase Realtime DB 获取两个变量

android - 在 Android 应用程序 Activity 之间使用单例?

android - 持久性 BottomSheet : Swipe to Expand Issue