본문 바로가기

안드로이드/androidstudio

[Android] 입력 text 한글자씩 지우는 방법

 오늘 포스팅은 backspace 버튼과 동일한 기능을 가진 버튼을 만드는 방법을 포스팅하겠습니다.

 edittext에 작성중이던 문자열을 한글자씩 지우고 싶을때 어떻게 하는지 알아보았습니다.

 

*substring

  string의 field 중 substring을 활용하는 것입니다. substring은 string.substring(begin, end) 로 사용합니다.

그럼 string을 begin 부터 end-1 까지만 저장하게됩니다.

public actual inline fun String.substring(startIndex: Int, endIndex: Int): String = (this as java.lang.String).substring(startIndex, endIndex)

android developers 에 substring의 설명은 다음과 같습니다. 

Returns a string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.

결론은 begin부터 end-1까지 반환하기때문에 backspace버튼을 만들고자 하면 기존 string의 길이 -1을 하면 한칸이 지워지게 됩니다. 실제 구현 코드는 아래와 같습니다.

insertNum.substring(0,insertNum.length - 1)

아래는 계산기 어플에 실제 지우기 버튼을 구현한 결과입니다.

계산기 지우기 버튼

 전체 지우기를 하고시을경우 string 자체를 null로 반환할수도 있고 substring을 통해 응용해서 만들수있으니 꼭 기억해두려합니다.

출처: https://developer.android.com/reference/java/lang/String#substring(int,%20int)