TextField
를 사용하면 사용자가 텍스트를 입력하고 수정할 수 있습니다. 사용할 수 있는 텍스트 필드에는 상태 기반 텍스트 필드와 값 기반 텍스트 필드의 두 가지 유형이 있습니다. 콘텐츠를 표시할 유형을 선택합니다.
TextField
의 상태를 관리하는 데 더 완전하고 안정적인 접근 방식을 제공하므로 상태 기반 텍스트 필드를 사용하는 것이 좋습니다. 다음 표에는 이러한 텍스트 필드 유형 간의 차이점이 간략하게 설명되어 있으며 상태 기반 텍스트 필드의 주요 이점이 포함되어 있습니다.
기능 |
값 기반 텍스트 필드 |
상태 기반 텍스트 필드 |
주 기반 혜택 |
---|---|---|---|
상태 관리 |
|
|
|
시각적 변환 |
표시된 텍스트의 모양을 수정하는 데 |
상태에 커밋되기 전에 사용자의 입력을 수정하는 데 |
|
라인 한도 |
|
|
|
보안 텍스트 필드 |
해당 사항 없음 |
|
|
이 페이지에서는 TextField
를 구현하고, TextField
입력을 스타일링하고, 키보드 옵션 및 시각적으로 사용자 입력을 변환하는 것과 같은 기타 TextField
옵션을 구성하는 방법을 설명합니다.
TextField
구현 선택
TextField
구현에는 두 가지 수준이 있습니다.
TextField
는 머티리얼 디자인 구현입니다. 이 구현은 Material Design 가이드라인을 따르므로 이 구현을 선택하는 것이 좋습니다.BasicTextField
를 사용하여 사용자가 하드웨어 또는 소프트웨어 키보드를 통해 텍스트를 수정할 수 있지만 힌트나 자리표시자와 같은 장식은 제공되지 않습니다.
TextField( state = rememberTextFieldState(initialText = "Hello"), label = { Text("Label") } )
OutlinedTextField( state = rememberTextFieldState(), label = { Text("Label") } )
스타일 TextField
TextField
및 BasicTextField
는 맞춤설정을 위한 많은 공통 매개변수를 공유합니다.
TextField
의 전체 목록은 TextField
소스 코드에서 확인할 수 있습니다. 다음은 유용한 매개변수의 일부 목록입니다.
textStyle
lineLimits
TextField( state = rememberTextFieldState("Hello\nWorld\nInvisible"), lineLimits = TextFieldLineLimits.MultiLine(maxHeightInLines = 2), placeholder = { Text("") }, textStyle = TextStyle(color = Color.Blue, fontWeight = FontWeight.Bold), label = { Text("Enter text") }, modifier = Modifier.padding(20.dp) )
디자인이 Material TextField
또는 OutlinedTextField
를 필요로 하는 경우 BasicTextField
보다 TextField
를 사용하는 것이 좋습니다. 하지만 Material 사양의 장식이 필요하지 않은 디자인을 빌드하는 경우 BasicTextField
를 사용해야 합니다.
브러시 API로 스타일 입력
TextField
에서 고급 스타일을 지정하려면 브러시 API를 사용하세요.
다음 섹션에서는 브러시를 사용하여 TextField
입력에 색상 그라데이션을 추가하는 방법을 설명합니다.
브러시 API를 사용하여 텍스트 스타일을 지정하는 방법에 관한 자세한 내용은 브러시 API로 고급 스타일 지정 사용 설정을 참고하세요.
TextStyle
를 사용하여 색상 그라데이션 구현
TextField
내에서 입력할 때 색상 그라데이션을 구현하려면 선택한 브러시를 TextField
의 TextStyle
로 설정하세요. 이 예시에서는 linearGradient
가 있는 내장 브러시를 사용하여 TextField
에 텍스트를 입력할 때 무지개 그라데이션 효과를 확인합니다.
val brush = remember { Brush.linearGradient( colors = listOf(Color.Red, Color.Yellow, Color.Green, Color.Blue, Color.Magenta) ) } TextField( state = rememberTextFieldState(), textStyle = TextStyle(brush = brush) )

TextField
콘텐츠에 적용되는 무지개 그라데이션 효과텍스트 필드 상태 관리
TextField
는 콘텐츠와 현재 선택에 TextFieldState
라는 전용 상태 홀더 클래스를 사용합니다. TextFieldState
는 아키텍처에 적합한 곳에 호이스팅되도록 설계되었습니다. TextFieldState
에서 제공하는 두 가지 주요 속성은 다음과 같습니다.
initialText
:TextField
의 콘텐츠입니다.initialSelection
: 커서 또는 선택 항목이 현재 있는 위치를 나타냅니다.
TextFieldState
이 onValueChange
콜백과 같은 다른 접근 방식과 다른 점은 TextFieldState
이 전체 입력 흐름을 완전히 캡슐화한다는 것입니다. 여기에는 올바른 지원 데이터 구조 사용, 필터 및 포매터 인라인, 다양한 소스에서 발생하는 모든 수정사항 동기화가 포함됩니다.
TextFieldState()
를 사용하여 TextField
에서 상태를 끌어올릴 수 있습니다. 이를 위해 rememberTextFieldState()
함수를 사용하는 것이 좋습니다.
rememberTextFieldState()
는 컴포저블에서 TextFieldState
인스턴스를 만들고, 상태 객체가 기억되도록 하며, 기본 저장 및 복원 기능을 제공합니다.
val usernameState = rememberTextFieldState() TextField( state = usernameState, lineLimits = TextFieldLineLimits.SingleLine, placeholder = { Text("Enter Username") } )
rememberTextFieldState
에는 빈 매개변수가 있거나 초기화 시 텍스트 값을 나타내기 위해 전달된 초기 값이 있을 수 있습니다. 후속 리컴포지션에서 다른 값이 전달되면 상태 값이 업데이트되지 않습니다. 초기화된 후 상태를 업데이트하려면 TextFieldState
에서 수정 메서드를 호출하세요.
TextField( state = rememberTextFieldState(initialText = "Username"), lineLimits = TextFieldLineLimits.SingleLine, )

TextField
에 초기 텍스트로 '사용자 이름'이 표시됩니다.TextFieldBuffer
로 텍스트 수정
TextFieldBuffer
는 StringBuilder
과 기능이 유사한 수정 가능한 텍스트 컨테이너 역할을 합니다. 텍스트 콘텐츠와 현재 선택에 관한 정보를 모두 보유합니다.
TextFieldBuffer
는 TextFieldState.edit
, InputTransformation.transformInput
, OutputTransformation.transformOutput
과 같은 함수의 수신기 범위로 자주 사용됩니다. 이러한 함수에서는 필요에 따라 TextFieldBuffer
를 읽거나 업데이트할 수 있습니다. 그런 다음 이러한 변경사항은 TextFieldState
에 커밋되거나 OutputTransformation
의 경우 렌더링 파이프라인으로 전달됩니다.
append
, insert
, replace
, delete
과 같은 표준 편집 기능을 사용하여 버퍼의 콘텐츠를 수정할 수 있습니다. 선택 상태를 변경하려면 selection: TextRange
변수를 직접 설정하거나 placeCursorAtEnd
또는 selectAll
와 같은 유틸리티 함수를 사용하세요. 선택 자체는 TextRange
로 표시되며, 여기서 시작 색인은 포함되고 종료 색인은 제외됩니다.
시작 값과 끝 값이 동일한 TextRange
(예: (3, 3)
)은 현재 선택된 문자가 없는 커서 위치를 나타냅니다.
val phoneNumberState = rememberTextFieldState() LaunchedEffect(phoneNumberState) { phoneNumberState.edit { // TextFieldBuffer scope append("123456789") } } TextField( state = phoneNumberState, inputTransformation = InputTransformation { // TextFieldBuffer scope if (asCharSequence().isDigitsOnly()) { revertAllChanges() } }, outputTransformation = OutputTransformation { if (length > 0) insert(0, "(") if (length > 4) insert(4, ")") if (length > 8) insert(8, "-") } )
TextFieldState
에서 텍스트 수정
상태 변수를 통해 상태를 직접 수정할 수 있는 몇 가지 방법이 있습니다.
edit
: 상태 콘텐츠를 수정할 수 있으며TextFieldBuffer
함수를 제공하여insert
,replace
,append
등의 메서드를 사용할 수 있습니다.val usernameState = rememberTextFieldState("I love Android") // textFieldState.text : I love Android // textFieldState.selection: TextRange(14, 14) usernameState.edit { insert(14, "!") } // textFieldState.text : I love Android! // textFieldState.selection: TextRange(15, 15) usernameState.edit { replace(7, 14, "Compose") } // textFieldState.text : I love Compose! // textFieldState.selection: TextRange(15, 15) usernameState.edit { append("!!!") } // textFieldState.text : I love Compose!!!! // textFieldState.selection: TextRange(18, 18) usernameState.edit { selectAll() } // textFieldState.text : I love Compose!!!! // textFieldState.selection: TextRange(0, 18)
setTextAndPlaceCursorAtEnd
: 현재 텍스트를 지우고 지정된 텍스트로 바꾼 후 커서를 끝에 설정합니다.usernameState.setTextAndPlaceCursorAtEnd("I really love Android") // textFieldState.text : I really love Android // textFieldState.selection : TextRange(21, 21)
clearText
: 모든 텍스트를 지웁니다.usernameState.clearText() // textFieldState.text : // textFieldState.selection : TextRange(0, 0)
다른 TextFieldState
함수는 TextFieldState
참조를 확인하세요.
사용자 입력 수정
다음 섹션에서는 사용자 입력을 수정하는 방법을 설명합니다.
입력 변환을 사용하면 사용자가 입력하는 동안 TextField
입력을 필터링할 수 있으며, 출력 변환은 사용자 입력이 화면에 표시되기 전에 형식을 지정합니다.
입력 변환으로 사용자 입력 필터링
입력 변환을 사용하면 사용자의 입력을 필터링할 수 있습니다. 예를 들어 TextField
가 미국 전화번호를 사용하는 경우 10자리 숫자만 허용해야 합니다. InputTransformation
의 결과는 TextFieldState
에 저장됩니다.
일반적인 InputTransformation
사용 사례를 위한 기본 제공 필터가 있습니다. 길이를 제한하려면 InputTransformation.maxLength()
를 호출하세요.
TextField( state = rememberTextFieldState(), lineLimits = TextFieldLineLimits.SingleLine, inputTransformation = InputTransformation.maxLength(10) )
맞춤 입력 변환
InputTransformation
는 단일 함수 인터페이스입니다. 맞춤 InputTransformation
를 구현할 때는 TextFieldBuffer.transformInput
를 재정의해야 합니다.
class CustomInputTransformation : InputTransformation { override fun TextFieldBuffer.transformInput() { } }
전화번호의 경우 숫자만 TextField
에 입력할 수 있도록 하는 맞춤 입력 변환을 추가합니다.
class DigitOnlyInputTransformation : InputTransformation { override fun TextFieldBuffer.transformInput() { if (!TextUtils.isDigitsOnly(asCharSequence())) { revertAllChanges() } } }
입력 변환 연결
텍스트 입력에 여러 필터를 추가하려면 then
확장 함수를 사용하여 InputTransformation
를 연결합니다. 필터는 순차적으로 실행됩니다. 결국 필터링될 데이터에 불필요한 변환이 적용되지 않도록 가장 선택적인 필터를 먼저 적용하는 것이 좋습니다.
TextField( state = rememberTextFieldState(), inputTransformation = InputTransformation.maxLength(6) .then(CustomInputTransformation()), )
입력 변환을 추가한 후 TextField
입력은 최대 10자리를 허용합니다.
표시되기 전에 입력 형식 지정
OutputTransformation
를 사용하면 화면에 렌더링되기 전에 사용자 입력을 포맷할 수 있습니다. InputTransformation
과 달리 OutputTransformation
을 통해 수행된 서식은 TextFieldState
에 저장되지 않습니다. 이전 전화번호 예시를 기반으로 적절한 위치에 괄호와 대시를 추가해야 합니다.

이는 값 기반 TextField
에서 VisualTransformation
를 처리하는 업데이트된 방식으로, 오프셋 매핑을 계산할 필요가 없다는 점이 주요 차이점입니다.
OutputTransformation
은 단일 추상 메서드 인터페이스입니다. 맞춤 OutputTransformation
를 구현하려면 transformOutput
메서드를 재정의해야 합니다.
class CustomOutputTransformation : OutputTransformation { override fun TextFieldBuffer.transformOutput() { } }
전화번호를 형식화하려면 OutputTransformation
에 색인 0에 여는 괄호, 색인 4에 닫는 괄호, 색인 8에 대시를 추가합니다.
class PhoneNumberOutputTransformation : OutputTransformation { override fun TextFieldBuffer.transformOutput() { if (length > 0) insert(0, "(") if (length > 4) insert(4, ")") if (length > 8) insert(8, "-") } }
다음으로 OutputTransformation
를 TextField
에 추가합니다.
TextField( state = rememberTextFieldState(), outputTransformation = PhoneNumberOutputTransformation() )
변환의 작동 방식
다음 다이어그램은 텍스트 입력에서 변환을 거쳐 출력으로 이어지는 흐름을 보여줍니다.

- 입력이 입력 소스에서 수신됩니다.
- 입력은 TextFieldState에 저장되는
InputTransformation
를 통해 필터링됩니다. - 입력은 서식을 위해
OutputTransformation
를 통해 전달됩니다. - 입력은
TextField
에 표시됩니다.
키보드 옵션 설정
TextField
를 사용하면 키보드 레이아웃과 같은 키보드 구성 옵션을 설정하거나 키보드에서 지원하는 경우 자동 수정을 사용 설정할 수 있습니다. 소프트웨어 키보드가 여기에 제공된 옵션을 준수하지 않을 경우 일부 옵션이 보장되지 않을 수도 있습니다. 다음은 지원되는 키보드 옵션의 목록입니다.
capitalization
autoCorrect
keyboardType
imeAction
추가 리소스
추천 서비스
- 참고: JavaScript가 사용 중지되어 있으면 링크 텍스트가 표시됩니다.
- Compose UI 설계
- 상태 및 Jetpack Compose
- Compose에 UI 상태 저장