簡體   English   中英

如何在單擊屏幕的任何其他部分時從editText中移除焦點

[英]How to remove focus from an editText on click any other portion of the screen

我的頁面上有兩個 EditText 視圖。 當我不點擊它們時,我想擺脫它們的焦點。 我無法讓它工作。 我試過這個。 我將此方法設置為除 EditTextView 之外的每個視圖但這僅擺脫了 cursor 和鍵盤視圖仍然突出顯示。 有沒有更輕松的方法來做到這一點。 有什么建議么。

public static void hideKeyboard(Activity activity) {
    InputMethodManager inputMethodManager =
            (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
    EditText editText = (EditText) (activity.getCurrentFocus());
    editText.setCursorVisible(false);
    inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}

嘗試移除焦點,只需添加觸摸偵聽器,它將檢測屏幕上的吸引力並移除焦點。

    rootView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
          if(event.getAction()==MotionEvent.ACTION_MOVE){

            }else if(event.getAction()==MotionEvent.ACTION_UP){


            }
        editText.setFocusableInTouchMode(false);
        editText.setFocusable(false);
        editText.clearFocus();

            return true;
        }
    });

@AtifAbbAsi,感謝您的回答。這就是我修復它的方法。

rootView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
    if(getCurrentFocus() instanceof EditText){
        EditText editText = (EditText) getCurrentFocus();
        hideKeyboard(LoginActivity.this);
        editText.clearFocus();
    }
    return false;
}
});

這是我為 hideKeyboard function 修改的代碼

    public void hideKeyboard(Activity activity) {
    InputMethodManager inputMethodManager =
            (InputMethodManager) activity.getSystemService(
                    Activity.INPUT_METHOD_SERVICE);
    if(getCurrentFocus() instanceof EditText){
        inputMethodManager.hideSoftInputFromWindow(
                activity.getCurrentFocus().getWindowToken(), 0);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM