본문 바로가기
개발자의 정보/Mobile App

EditText focus issue.

by pastory 2020. 2. 1.

If you want to clear focus on EditText view when you click or touch other places.

Insert below code in your Activity you want to apply.

 

@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 );
}

When activity start, If you don’t want to get auto focus, insert below property in your layout xml element wrapping EditText element.

 

android:focusable="true"
android:focusableInTouchMode="true"

댓글