본문 바로가기
Android Studio

[Android, Kotlin] 안드로이드 EditText 글자 수 세기(TextInputLayout + TextInputEditText)

by 열정적인 이찬형 2022. 9. 29.

AlertDialog를 이용해서 어떤 정보에 대하여 글자수 제한을 걸고 몇 글자를 작성하였는지 확인하기 찾아보다가 정리한 내용입니다.


사용법

 

저는 EditText + TextView를 이용하지 않고 TextInputLayout + TextInputEditText를 조합하여 따로 코드를 구현하지 않고 글자 개수를 볼 수 있도록 구현하였습니다.

 

간단하게 구현한 화면입니다.

간단하게 구현한 코드입니다.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    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">

    <com.google.android.material.textfield.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:counterEnabled="true"
        app:counterMaxLength="20"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" >
        <com.google.android.material.textfield.TextInputEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/white"
            android:maxLength="20"/>
    </com.google.android.material.textfield.TextInputLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

TextInputLayout + TextInputEditText으로 구현하였습니다.

 

TextInputLayout

CounterMaxLenght = 20

CounterEnable = true

설정하여 TextInputLayout에서 글자수를 세기로 설정합니다.

 

TextInputEditText

maxLength = 20

설정하여 Counter와 동일한 글자수만큼 작성할 수 있도록 합니다.

 

이제 TextInputEditText에 글을 작성하게 되면

 

TextInputEditText에서 작성된 내용에 따라 TextInputLayout에서 글자수를 표현하게 됩니다.

 

아래 링크에 들어가셔서 더 자세한 내용들을 확인하실 수 있습니다.

 

TextInputLayout  |  Android Developers

 

developer.android.com

 

 

TextInputEditText  |  Android Developers

 

developer.android.com

 

 

더 좋은 방법이 존재한다면 댓글로 남겨주시면 감사하겠습니다.

댓글