예제를 시작하기 전에 안드로이드의 TextInputLayout이 무엇인지 먼저 알아보겠습니다. TextInputLayout은 LinearLayout을 확장한 위젯으로, EditText를 감싸는 래퍼(wrapper) 역할을 하며 포커스 시 힌트가 위로 떠오르는 플로팅 힌트(floating hint) 애니메이션 효과를 제공합니다.
이 글에서는 안드로이드에서 TextInputLayout을 구현하는 방법을 단계별로 살펴보겠습니다.
1단계: 새 프로젝트 생성
Android Studio에서 File ⇒ New Project를 선택하여 새 프로젝트를 만들고, 필요한 모든 정보를 입력해 프로젝트를 생성합니다.
2단계: 레이아웃 파일 작성
res/layout/activity_main.xml에 아래 코드를 추가합니다.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "https://schemas.android.com/apk/res/android"
xmlns:tools = "https://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity"
android:background = "#dde4dd"
android:orientation = "vertical">
<android.support.design.widget.TextInputLayout
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:id = "@+id/layoutEmail"
android:layout_marginTop = "8dp"
android:layout_marginStart = "8dp"
android:layout_marginEnd = "8dp"
style = "@style/Widget.MaterialComponents.TextInputLayout.FilledBox">
<android.support.design.widget.TextInputEditText
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:id = "@+id/email"
android:hint = "Enter Email id"
android:inputType = "textEmailAddress"/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:id = "@+id/layoutPassword"
android:layout_marginTop = "8dp"
android:layout_marginStart = "8dp"
android:layout_marginEnd = "8dp"
style = "@style/Widget.MaterialComponents.TextInputLayout.FilledBox">
<android.support.design.widget.TextInputEditText
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:id = "@+id/password"
android:hint = "Password"
android:inputType = "textPassword"/>
</android.support.design.widget.TextInputLayout>
<Button
android:id = "@+id/click"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_gravity = "center"
android:text = "Click"></Button>
</LinearLayout>위 코드에서는 이메일 입력용과 비밀번호 입력용 TextInputEditText 두 개와 버튼 하나를 배치했습니다. 버튼을 클릭하면 EditText에서 입력값을 가져와 Toast 메시지로 화면에 표시합니다.
3단계: MainActivity 작성
src/MainActivity.java에 아래 코드를 추가합니다.
package com.example.andy.myapplication;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
EditText email, password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
email = findViewById(R.id.email);
password = findViewById(R.id.password);
Button click = findViewById(R.id.click);
click.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!email.getText().toString().isEmpty() && (!password.getText().toString().isEmpty())) {
Toast.makeText(MainActivity.this,
"you have entered email id " + email.getText().toString()
+ " Password " + password.getText().toString(),
Toast.LENGTH_LONG).show();
} else {
email.setError("Please Enter Email id");
password.setError("Please Enter Pass word");
}
}
});
}
}버튼 클릭 시 이메일과 비밀번호 필드가 모두 채워져 있으면 입력된 값을 Toast로 출력하고, 비어 있으면 setError()를 통해 각 필드에 오류 메시지를 표시하도록 처리했습니다.
4단계: 디자인 지원 라이브러리 추가
build.gradle 파일을 열고 design support library 의존성을 추가합니다.
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.example.andy.myapplication"
minSdkVersion 15
targetSdkVersion 28
compileSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:design:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}android.support.design.widget.TextInputLayout 대신 com.google.android.material.textfield.TextInputLayout을 사용하고, 의존성으로 implementation 'com.google.android.material:material:1.x.x'를 추가하는 것이 좋습니다.앱 실행 및 결과 확인
이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 모바일 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 Run(실행) 아이콘을 클릭하고, 목록에서 자신의 모바일 기기를 선택하면 기기에 아래와 같은 초기 화면이 표시됩니다.

위 화면은 앱의 초기 화면입니다. 이제 이메일과 비밀번호를 입력한 후 버튼을 클릭하면 아래와 같이 입력한 값이 Toast로 표시됩니다.

반대로 EditText의 내용을 모두 지운 상태에서 버튼을 클릭하면, 각 입력 필드에 오류 메시지가 나타나는 것을 확인할 수 있습니다.
