[Android/Kotlin] IP 주소 입력 EditText 구현하기

SoyoungLee·2022년 5월 25일
0

안드로이드/코틀린

목록 보기
19/68
post-thumbnail

💌 [안드로이드/코틀린] IP 주소 입력 EditText 구현하기

EditText 1개에 숫자와 . 입력 가능한 문자 타입 제한하기

                <EditText
                    android:id="@+id/et_ip"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:digits="0123456789."
                    android:imeOptions="actionNext"
                    android:inputType="number"
                    android:maxLength="15"
                    />

inputType 을 number로 설정하고
digits 에 "1234567890." 로 EditText 에 입력될 수 있는 문자를 지정한다

이렇게 구현하면 아이피를 입력받는 하나의 에디트 텍스트가 구현 가능한데 예외 상황을 발견했다

(Android Galaxy Tab S3 : SM-T820 기종)

키패드에 .이 없어서 입력이 불가능했다 ㅠ_ㅠ

그래서 IP 입력 창 레이아웃을 EditText를 나누고 .을 고정시킨 걸로 변경했다

EditText 4개와 구분 . TextView 3개로 레이아웃 구성

<LinearLayout
	android:layout_width="match_parent"
	android:layout_height="wrap_content"
	android:layout_weight="4"
	android:orientation="horizontal">

                <EditText
                    android:id="@+id/et_ip1"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:background="@null"
                    android:imeOptions="actionNext"
                    android:inputType="number"
                    android:lines="1"
                    android:maxLength="3"
                    android:gravity="center"
                    android:text="111" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="bottom"
                    android:text="." />

                <EditText
                    android:id="@+id/et_ip2"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:background="@null"
                    android:gravity="center"
                    android:imeOptions="actionNext"
                    android:inputType="number"
                    android:lines="1"
                    android:maxLength="3"
                    android:text="112" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="bottom"
                    android:text="."
                    android:textColor="@color/black"
                    android:textSize="18dp"
                    custom:font_type="medium" />

                <EditText
                    android:id="@+id/et_ip3"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:background="@null"
                    android:gravity="center"
                    android:imeOptions="actionNext"
                    android:inputType="number"
                    android:lines="1"
                    android:maxLength="3"
                    android:text="111"/>

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="bottom"
                    android:text="."/>

                <EditText
                    android:id="@+id/et_ip4"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:background="@null"
                    android:gravity="center"
                    android:imeOptions="actionNext"
                    android:inputType="number"
                    android:lines="1"
                    android:maxLength="3"
                    android:text="111"/>

0~255까지만 입력 범위를 제한하여 유효성 체크

255를 넘어가는 숫자를 입력하면 입력된 숫자를 지워준다

String 타입을 Integer로 바꿔주는거라 에디트 창에 입력했다가 숫자를 다 지우면 에러가 뜸


java.lang.numberformatexception: for input string: ""

숫자가 아닌 타입을 숫자로 변환할 때 생기는 에러라고 한다

찾아보니 Int 의 허용 범위는 -2,147,483,648 ~ 2,147,483,647 인데 이 범위를 초과해서 Double 형태로 선언하면 해결이 된다고 한다

나는 그냥 에디트 창에 숫자 입력이 되어있을 때만 유효성 체크 함수를 하게 if 문을 추가해서 해결했다

fun checkEtRange(et: EditText) {
        if (et.text.isNotEmpty()){
            if (Integer.parseInt(et.text.toString()) > 255) {
                et.setText(et.text.substring(0, et.length() - 1))
                et.setSelection(et.length())
                Toast.makeText(context, 0~255까지의 숫자를 입력해주세요., Toast.LENGTH_SHORT).show()
            }
        }
    }

입력 완료하면 다음 EditText로 포커스 이동

TextWatcher 를 이용하여 첫번째 아이피 주소를 세자리 다 입력 완료하면 자동으로 포커스가 다음 에디트 텍스트로 이동하게 했다
(한자리나 두자리면 셀프 이동 ㅎㅎ)

et_ip1.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
                    if(s!!.length>=3) et_ip2.requestFocus()
            }
            override fun afterTextChanged(s: Editable?) {
            		checkEtRange(et_ip2)
            }
        })

참고 : https://intrepidgeeks.com/tutorial/android-ip-address-input-box-implementation-method-example-code
https://crazykim2.tistory.com/522
https://itstudy-mary.tistory.com/345

profile
Android Developer..+ iOS 슬쩍 🌱 ✏️끄적끄적,,개인 기록용 👩🏻‍💻

0개의 댓글