본문 바로가기
안드로이드 자바

[Android][Java] EditText 에서 작성 가능한 숫자 범위 제한하기

by teamnova 2023. 8. 5.

안녕하세요 오늘은 EditText 에서 작성 가능한 숫자 범위 제한하는 방법을 알아보겠습니다.

오늘 작성할 파일은 다음과 같습니다.

 

activity_main.xml을 다음과 같이 작성해줍니다.

<?xml version="1.0" encoding="utf-8"?>
<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"
    tools:context=".MainActivity"
    android:orientation="vertical"
    >
    
        <EditText
            android:id="@+id/people"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:layout_margin="20dp"
            android:background="#2FA9A9A9"
            android:hint="모집 할 인원수 (2 ~20)"
            android:inputType="number"
            android:paddingLeft="5dp" />



    <TextView
        android:layout_width="match_parent"
        android:layout_height="25dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:text="인원수는 최소 2명부터 최대 20명까지 가능합니다"
        android:textColor="#3E2807"
        android:paddingLeft="5dp"/>

</LinearLayout>

 

MainActivty 코드를 다음과 같이 작성해줍니다.

package com.example.test;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

    private EditText  people;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        people = findViewById(R.id.people);


        people.addTextChangedListener(new TextWatcher() {
            //모임 인원수 적는 et의 텍스트가 변경될 때
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            //            @SuppressLint("ResourceType")
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                //텍스트가 변경될 때마다 함수 호출

                if(people.getText().toString().length()>0) {
                    // 작성되어 있던 값을 지울 때 pareInt(" ") 에서 에러가 나기 때문에 위와 같은 과정 필요

                    if (Integer.parseInt(people.getText().toString()) > 20) {
                        // 20명 초과일 때
                        people.setText("20");
                        //et가 20으로 변경됨

                    }

                    if (Integer.parseInt(people.getText().toString()) < 2) {
                        // 2 미만일 때
                        people.setText("2");
                        // et가 2로 변경됨

                    }
                }


            }

            @Override
            public void afterTextChanged(Editable editable) {


            }
        });

    }
}

 

위와 같은 단계를 거친 후 실행된 결과는 다음과 같습니다.