상세 컨텐츠

본문 제목

[android] EditText에 자동 포커스 막기 및 초기 키보드 자동 실행 막기

스마트기기개발관련/안드로이드 개발

by AlrepondTech 2018. 2. 28. 11:21

본문

반응형
728x170


////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


출처: http://egloos.zum.com/uknowapps/v/1812401


EditText에 자동 포커스 막기 및 초기 키보드 자동 실행 막기

1. EditText에 자동 포커스 막기

EditText를 실행하면 자동으로 포커스가 가는데 이를 막고자 한다면
EditText이외의 view에 아래와 같은 속성을 추가한다. 일반적으로
EditText 상위 view 즉 Layout에 속성을 추가할 수 있다.

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

2. EditText 사용시 초기 키보드 자동 실행 막기

EditText를 사용해 프로그래밍할 때 초기 키보드 자동 실행을 막고자 한다면
마니페스트 파일에 Activity 태그에 아래 속성을 추가한다.

android:windowSoftInputMode="stateAlwaysHidden"

3. EditText에 데이터를 입력하고 버튼을 눌렀을 때 같은 Activity내에서
   데이터를 ListView에 추가하는 상황에서 키보드가 계속 실행되는 것 막기


데이터 입력 후 버튼을 누른 후 이벤트 처리하는 핸들러에 아래 코드 추가

//키보드 숨기기
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);


////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


출처: https://stackoverflow.com/questions/4828636/edittext-clear-focus-on-touch-outside



Simply define two properties of parent of that EditText as :

android:clickable="true"
android:focusableInTouchMode="true"

So when user will touch outside of EditText area, focus will be removed because focus will be transferred to parent view.


---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------


or Me Below things Worked -

1.Adding android:clickable="true" and android:focusableInTouchMode="true" to the parentLayout of EditTexti.e android.support.design.widget.TextInputLayout

<android.support.design.widget.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:clickable="true"
    android:focusableInTouchMode="true">
<EditText
    android:id="@+id/employeeID"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ems="10"
    android:inputType="number"
    android:hint="Employee ID"
    tools:layout_editor_absoluteX="-62dp"
    tools:layout_editor_absoluteY="16dp"
    android:layout_marginTop="42dp"
    android:layout_alignParentTop="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_marginRight="36dp"
    android:layout_marginEnd="36dp" />
    </android.support.design.widget.TextInputLayout>

2.Overriding dispatchTouchEvent in Activity class and inserting hideKeyboard() function

@Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View view = getCurrentFocus();
            if (view != null && view instanceof EditText) {
                Rect r = new Rect();
                view.getGlobalVisibleRect(r);
                int rawX = (int)ev.getRawX();
                int rawY = (int)ev.getRawY();
                if (!r.contains(rawX, rawY)) {
                    view.clearFocus();
                }
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    public void hideKeyboard(View view) {
        InputMethodManager inputMethodManager =(InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

3.Adding setOnFocusChangeListener for EditText

EmployeeId.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    hideKeyboard(v);
                }
            }
        });
shareimprove this answer


////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


출처: http://gogorchg.tistory.com/entry/Android-EditText-%EC%9E%90%EB%8F%99-%ED%8F%AC%EC%BB%A4%EC%8A%A4-%EC%A0%9C%EA%B1%B0



화면이 실행 되면 초반에 EditText에 자동 포커스가 되죠.


이부분을 제거하고 싶으실 경우 아래와 같이 해보세요.



<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="true"
android:focusableInTouchMode="true"
android:gravity="center_vertical"
android:orientation="vertical"
>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp">

<android.support.v7.widget.AppCompatEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@color/_121212"
android:textSize="@dimen/_15sp"
/>
</android.support.design.widget.TextInputLayout>
</LinearLayout>

아래 두줄을 EditText 에 넣는게 아니라 그걸 감싸고 있는 LinearLayout에 넣어주세요.

그럼 포커스가 LinearLayout으로 가게 됩니다.


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


참고하세요.


http://stackoverflow.com/questions/1555109/stop-edittext-from-gaining-focus-at-activity-startup



출처: http://gogorchg.tistory.com/entry/Android-EditText-자동-포커스-제거 [항상 초심으로]


////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


출처: http://theeye.pe.kr/archives/1423


[Android] EditText에 자동으로 포커스(Focus)되는것 막기

화면에서 EditText가 있을 경우 엑티비티가 생성되면서 자동으로 포커스가 가는 경우가 있습니다. 사실 경우가 있다기 보다는 무조건 포커스가 갑니다. 이것이 좋게 느껴지지는 않는군요. 자동으로 생기는 포커스를 제거하기 위해서는 다양한 방법을 사용할 수 있지만 다음의 방법이 가장 간단하지 않을까 생각합니다.

위에서 볼 수 있듯이 가장 바깥에 있는 LinearLayout에 다음의 두개의 옵션을 추가하는것만으로 EditText에 포커스가 자동으로 가는것을 막을 수 있습니다.

위의 옵션은 가장 바깥쪽 엘리먼트인 LinearLayout이 우선적으로 포커스를 받아버림으로써 EditText로 포커스가 가는것을 막는 설정입니다. 원래 LinearLayout은 포커스를 받는 대상이 아니지만 포커스를 받게함과 동시에 LinearLayout은 특성상 포커스를 받아도 티가 나지 않기 때문에 별 문제 없이 사용할 수 있습니다.

만약에 위와 같은 구조로 화면이 구성되지 않아 위의 방법을 구현하기 힘들경우 눈에 보이지 않는 LinearLayout을 하나 추가해 주시면 됩니다.

예전에는 엑티비티가 뜨는 순간부터 오른쪽의 모습을 가지던것이 왼쪽과 같이 자동으로 포커스가 가는것이 사라졌습니다.


[좌 : 자동포커스 제거 후 / 우 : 자동포커스 제거 전]

참고: http://stackoverflow.com/questions/1555109/stop-edittext-from-gaining-focus-at-activity-startup


////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////





반응형
그리드형


관련글 더보기

댓글 영역