오늘은 앱을 개발하다보면 언젠가 한번은 쓰는
TextView나 EditText에서 글자 수를 제한하는 방법에 대해 포스팅 해보겠습니다
1. 글자 수 제한
1
2
3
4
5
|
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="예제 텍스트입니다"
android:maxLength="5"/>
|
글자 수 제한의 경우 간단히 maxLength를 사용합니다.
이때 글자 수는 공백 포함인 것을 알 수 있습니다.
EditText의 경우 5글자를 작성하면 더이상 써지지 않습니다!
2. 글자 수 제한 + 줄임표
1
2
3
4
5
6
7
|
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="예제 텍스트입니다"
android:ems="5"
android:maxLines="1"
android:ellipsize="end"/>
|

줄임표를 사용할 경우 ellipsize 속성을 씁니다. end는 텍스트 뒷부분을 줄이기 위해서구요
ellipsize 속성을 썼을 때 maxLength를 사용하면 줄임표가 제대로 뜨지 않더라구요
ems를 써주었습니다. ems는 공백 포함하지 않고 글자 수를 제한하는 것을 알 수 있죠!
예전에는 singleLine 속성을 함께 써주었는데 지금은 deprecated 되어서 maxLines="1" 을 씁니다
3. 문장 줄 수 제한
위에 써준 maxLines 속성을 사용하면 간단히 줄 수를 제한할 수 있습니다.
ellipsize를 함께 써주면 동일하게 문장 뒤를 줄여줍니다!
4. TextView width 에 따라 제한
앱을 개발하다보니 글자 수 말고도 TextView 너비를 제한하고 싶을 때가
저의 경우에는 더 많았기 때문에! 같이 소개해 드리겠습니다.
1
2
3
4
5
|
<TextView
android:layout_width="50dp"
android:layout_height="wrap_content"
android:text="예제 텍스트입니다"
android:maxLines="2"/>
|
먼저 단순히 layout_width를 고정시켜 주는 예입니다.
이때 maxLines를 꼭 설정해주셔야 해요.
쓰지 않으면 텍스트가 단순히 너비에 맞추어 줄바꿈됩니다.
+ 추가 (ConstraintLayout)
1
2
3
4
5
6
7
8
9
10
11
|
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintWidth_percent="0.5"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:text="예제 텍스트입니다예제 텍스트입니다"
android:maxLines="1"
android:ellipsize="end"/>
|
이 예시는 ConstraintLayout을 사용할 경우만! 입니다
layout_width를 0dp로 설정하고
layout_constraintWidth_percent를 설정해주세요.
여기서 1이 최대 너비, 즉 match_parent라고 생각하시면 되고, 최소는 0입니다.
제가 쓴 0.5 속성은 화면의 반이겠죠. 보시는 바와 같이 화면의 반만 차지하고 글자수가 줄어듭니다.
ConstraintLayout은 비교적 최근에 나온 Layout이죠
익혀놓으면 정말 편리합니다. 추후에 ConstraintLayout에 대해서도 포스팅 해야겠네요!
오늘은 여기까지 입니다
'Android' 카테고리의 다른 글
[Android] Glide 라이브러리 사용하기 (ImageView에 이미지 리소스, GIF 넣기) (0) | 2020.07.14 |
---|---|
[Android] TextWatcher 사용하기 - EditText 입력 변경 이벤트 탐지 (Kotlin) + 무한루프 해결법 (0) | 2019.09.08 |
[Android] Retrofit 2.0 사용 방법 (Java, Kotlin) - 2. Call 동기, 비동기 (6) | 2019.09.03 |
[Android] Button 클릭 효과 주기 (버튼 누르는 효과, XML) (0) | 2019.08.06 |
[Android] Retrofit 2.0 사용 방법 (Kotlin) - 1. 시작하기 (0) | 2019.07.28 |