2016-06-08 193 views
0

按下Back按鈕或Done按鈕時,隱藏softInputKeyboard的操作是隱藏鍵盤,當用戶點擊EditText時隱藏鍵盤。所以我創建了一個BaseActivity並在其中編寫了以下代碼。Android:觸摸EditText時隱藏軟鍵盤

public class BaseActivity extends AppCompatActivity { 

    @Override 
    public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) { 
     super.onCreate(savedInstanceState, persistentState); 
    } 

    @Override 
    public boolean dispatchTouchEvent(MotionEvent ev) { 
     boolean handleReturn = super.dispatchTouchEvent(ev); 

     View view = getCurrentFocus(); 

     int x = (int) ev.getX(); 
     int y = (int) ev.getY(); 

     if (view instanceof EditText) { 
      EditText innerView = (EditText) getCurrentFocus(); 

      if (ev.getAction() == MotionEvent.ACTION_UP && 
        !getLocationOnScreen(innerView).contains(x, y)) { 

       InputMethodManager input = (InputMethodManager) 
         getSystemService(Context.INPUT_METHOD_SERVICE); 
       input.hideSoftInputFromWindow(getWindow().getCurrentFocus() 
         .getWindowToken(), 0); 
      } 
     } 

     return handleReturn; 
    } 

    protected Rect getLocationOnScreen(EditText mEditText) { 
     Rect rect = new Rect(); 
     int[] location = new int[2]; 

     mEditText.getLocationOnScreen(location); 

     rect.left = location[0]; 
     rect.top = location[1]; 
     rect.right = location[0] + mEditText.getWidth(); 
     rect.bottom = location[1] + mEditText.getHeight(); 

     return rect; 
    } 
} 

爲MyActivity擴展上述類,它在其佈局上對EditTexts正常工作。但是,當我彈出一個AlertDialog與自定義佈局,其中有許多EditText的時候它不起作用。

我觸摸了AlertDialog中的EditText,甚至是對話框的前景,但鍵盤沒有被解僱。

它在這種情況下怎麼可能隱藏?

回答

0

使用下面的代碼。它爲我

@Override 
public boolean dispatchTouchEvent(MotionEvent event) { 
    if (event.getAction() == MotionEvent.ACTION_DOWN) { 
     View v = getCurrentFocus(); 
     if (v instanceof EditText) { 
      Rect outRect = new Rect(); 
      v.getGlobalVisibleRect(outRect); 
      if (!outRect.contains((int)event.getRawX(), (int)event.getRawY())) { 
       v.clearFocus(); 
       InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); 
       imm.hideSoftInputFromWindow(v.getWindowToken(), 0); 
      } 
     } 
    } 
    return super.dispatchTouchEvent(event); 
} 
+0

我想你沒有理解我的問題,上述...當我觸摸到了一個AlertDialog具有自定義佈局的鍵盤應該被隱藏 – user1799171

0

有兩件事情要記住,以實現這一目標 -

假設XML struture就像

<ViewGroup focusable=true focusInTouchMode=true> 
    <EditText /> 
</ViewGroup> 
  1. 使母公司的ViewGroup爲可聚焦=真& focusInTouchMode = true
  2. set onfocuschangelistener()上的EditText,即

    edittext.editCaption.setOnFocusChangeListener(new View.OnFocusChangeListener() { 
        @Override 
        public void onFocusChange(View v, boolean hasFocus) { 
         InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); 
         inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), 0); 
        } 
    });