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

[Android][Java] EditText 글자 수 제한하기

by teamnova 2023. 8. 20.

안녕하세요 오늘은 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/title"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_marginTop="30dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:background="#2FA9A9A9"
        android:hint="제목"
        android:paddingLeft="5dp"
        android:maxLength="14"
        />

    <TextView

        android:layout_width="match_parent"
        android:layout_height="25dp"
        android:layout_marginTop="5dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:text="제목은 공백 포함 최대 14글자만 입력 가능합니다"
        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  title;

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


    }
}

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