[Android] Focus

Krrong·2022년 5월 25일
0

Android

목록 보기
13/14

📌 Intro

이전에 recyclerView에서 원하는 아이템을 검색하기 위해 editText를 이용했었다. editText가 있는 액티비티로 넘어가게 되면 바로 editText에 Focus가 가면서 키보드가 올라온다. 이 부분이 사용자가 어플리케이션을 이용할 때 불편한 부분이 될 수 있을 것 같아 키보드가 바로 올라오지 않도록 수정하는 방법을 알아보고 정리하려고 한다.

📌 Focus란?

먼저 Focus에 대해 알아보도록 하자.

Intro에서 이야기한 것 처럼 사용자가 editText를 누르게 되면 키보드가 나오면서 상호작용 할 수 있게 되며 이 때 editText가 Focus를 갖게 되는 것이다.

Focusable의 속성이 true로 되어 있는 뷰가 사용자와 상호작용하기 시작할 때 그 뷰가 Focus를 가졌다라고 한다. editText는 default로 Focusable의 속성이 true이다. 때문에 editText가 있는 액티비티로 넘어가면 바로 키보드가 올라오는 것이다.

만약 다른 뷰에 Focus를 주고 싶다면 임의로 속성을 변경해주어야 한다.

📌 Focus 변경하기

1. xml에서 변경하기

<LinearLayout
    android:id="@+id/linearLayout_focus"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:layout_width="0dp"
    android:layout_height="0dp"/>

레이아웃에서 Foucs를 주고 싶은 뷰에 android:focusable="true"android:focusableInTouchMode="true" 를 추가해주도록 하자.

2. 코드로 변경하기

findViewById() 를 통해 찾은 View에 setFocusable(true)setFocusableInTouchMode(true) 메서드를 이용하여 Focus를 줄 수 있다.

📌 자동 포커싱

만약 액티비티에서 Focus를 가질 수 있는 뷰가 여러개 있을 때 가장 첫 번째 뷰에 Focus를 부여한다. 그래서 액티비티에 editText가 있다면 자동으로 해당 뷰에 Focus가 가게되고 키보드가 올라오는 것이다.

이를 해결하기 위해서는 editText보다 앞에 있는 뷰에 위에서 언급한 속성을 부여주해면 된다.

예를 들면 다음과 같다.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:focusable="true"
    android:focusableInTouchMode="true"
    tools:context="">

	<EditText
	        android:id="@+id/editText"
	        android:layout_width="match_parent"
	        android:layout_height="0dp"
	        android:layout_weight="1"
	        android:ems="10"
	        android:hint="찾는 물품 검색"
	        android:inputType="textPersonName" />
</LinearLayout>

위 코드를 보면 editText가 있지만 android:focusable="true"android:focusableInTouchMode="true"를 이용하여 editText보다 먼저 나오는 LinearLayout에 Focus를 줄 수 있고 자동으로 키보드가 올라오는 것을 막을 수 있다.

📌 참고

[1] https://satisfactoryplace.tistory.com/9

0개의 댓글