[Android/Kotlin] 안드로이드 TextInputLayout 사용해보기
안녕하세요. 오늘은 TextInputLayout에 사용법에 대해서 알아보겠습니다.
TextInputLayout은 EditText를 기반으로 좀 더 유연한 동작을 보여주는 레이아웃입니다.
TextInputEditText를 감싸고 있습니다.
TextInputLayout을 사용하기 위해서는 Material Library가 추가되어 있어야합니다.
implementation 'com.google.android.material:material:1.2.1'
기본적인 사용법은 아래와 같습니다.
<?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"
android:orientation="vertical"
android:padding="16dp"
tools:context=".MainActivity">
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="이메일..."
/>
</com.google.android.material.textfield.TextInputLayout>
</LinearLayout>
TextInputEditText에 Hint 값을 "이메일..."로 주었습니다.
아래와 같이 EditText에 포커스가 주어질때 Hint 값이 TextInputLayout의 라벨로 이동합니다.
TextInputLayout 의 스타일은 기본적으로 두가지가 있습니다.
위에 보이는 스타일이 기본 스타일인 FilledBox 이고, 다른 하나는 OutlinedBox 스타일이 있습니다.
아래와 같이 비밀번호를 입력하는 EditText를 추가했습니다.
Style값에 Widget.MaterialComponents.TextInputLayout.OutlinedBox를 적용했습니다.
적용된 모습은 아래와 같습니다.
<com.google.android.material.textfield.TextInputLayout
style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="비밀번호..."
/>
</com.google.android.material.textfield.TextInputLayout>
TextInputLayout 의 몇가지 속성에 대해서 설명드리겠습니다.
비밀번호 같은 경우에는 입력 후 보이지 않게 처리하기 위해서 inputType="textPassword"를 EditText 속성 값으로 추가하고, 비밀번호를 보기위한 토글 버튼을 만들기 위해 passwordToggleEnabled="true" TextInputLayout속성으로 추가해 줍니다.
<com.google.android.material.textfield.TextInputLayout
style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
app:passwordToggleEnabled="true"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="비밀번호..."
android:inputType="textPassword"
/>
</com.google.android.material.textfield.TextInputLayout>
TextInputLayout은 입력 텍스의 길이를 카운트할 수 있는 기능도 있습니다.
닉네임을 입력하는 TextInputLayout 하나 더 추가했습니다. 여기에 counterEnabled="true" 속성과, counterMaxLength="10" 속성을 추가합니다.
<com.google.android.material.textfield.TextInputLayout
style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
app:counterEnabled="true"
app:counterMaxLength="10"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="닉네임..."
android:inputType="text"
/>
</com.google.android.material.textfield.TextInputLayout>
아래와 같이 입력 텍스트 길이가 10자리를 넘어가면 빨간색으로 경고를 표시해 줍니다.
사용자가 10자리 이상을 입력하지 못하게 TextInputEditText에 maxLength="10"속성을 입력 합니다.
그러면 아래와 같이 10자리에서 멈추게 할 수 있습니다.
마지막으로 TextInputLayout의 Error 기능이 있습니다.
사용자가 입력 후 어떠한 액션을 시작하기전에 Validate을 할때가 있습니다. 예를들어 로그인시에 이메일 형식을 알맞게 입력했는지 체크할 필요가 있습니다. 이메일 형식이 올바르지 않으면 Error 메세지를 표시해주는 방법에 대해서 말씀드리겠습니다.
EditText에 입력된 값을 검사하여, 값이 없거나 잘 못 되었을 때 setError()를 호출하여
에러 메시지를 전달 할 수 있습니다. 아래 코드를 참고해 주세요.
[MainActivity.kt]
class MainActivity : AppCompatActivity() {
private var _binding: ActivityMainBinding? = null
private val binding get() = _binding!!
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
_binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.btnLogin.setOnClickListener {
if (!validateEmail()) {
return@setOnClickListener
}
// Login Action
Toast.makeText(this, "로그인 GO!!", Toast.LENGTH_SHORT).show()
}
}
private fun validateEmail(): Boolean {
val value: String = binding.tilEmail.editText?.text.toString()
val emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+"
return if (value.isEmpty()) {
binding.tilEmail.error = "이메일을 입력해주세요."
false
} else if (!value.matches(emailPattern.toRegex())) {
binding.tilEmail.error = "이메일 형식이 잘 못 되었습니다."
false
} else {
binding.tilEmail.error = null
binding.tilEmail.isErrorEnabled = false
true
}
}
override fun onDestroy() {
super.onDestroy()
_binding = null
}
}
[activity_main.kt]
<?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"
android:orientation="vertical"
android:padding="16dp"
tools:context=".MainActivity">
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/til_email"
style="@style/Widget.MaterialComponents.TextInputLayout.FilledBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp">
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="이메일..."
/>
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
app:passwordToggleEnabled="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp">
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="비밀번호..."
android:inputType="textPassword"
/>
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
app:counterEnabled="true"
app:counterMaxLength="10"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="닉네임..."
android:inputType="text"
android:maxLength="10"
/>
</com.google.android.material.textfield.TextInputLayout>
<Button
android:id="@+id/btn_login"
android:text="로그인"
android:textSize="20sp"
android:textStyle="bold"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
'기리's Android 이야기' 카테고리의 다른 글
[Android/Error] 안드로이드 NullPointerException: WindowInsetsController... (1) | 2021.02.04 |
---|---|
[Android/Kotlin] 안드로이드 Multi Selection RecyclerView 만들기 (0) | 2021.02.02 |
[Android/Kotlin] 안드로이드 Room Database 사용하기(2) Select... (1) | 2021.02.01 |
[Android/Error] 안드로이드 ViewModelProvider 에러발생 (0) | 2021.01.31 |
[Android/Kotlin] 안드로이드 Section(Group) RecyclerView 만들기 (1) | 2021.01.31 |
댓글