Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

안드로이드 앱에서 비밀번호 표시·숨김 전환 기능 구현하기 (단계별 가이드)

로그인 화면을 개발하다 보면 사용자가 입력한 비밀번호를 확인할 수 있도록 '표시/숨김' 전환 기능이 필요한 경우가 많습니다. 이번 튜토리얼에서는 안드로이드에서 비밀번호를 숨기고 보이는 상태를 자유롭게 전환하는 방법을 단계별로 알아보겠습니다.

1단계: 새 프로젝트 생성

Android Studio에서 File → New Project 메뉴로 이동한 뒤, 새 프로젝트 생성에 필요한 모든 세부 정보를 입력하여 프로젝트를 만듭니다.

2단계: 레이아웃 파일 작성 (activity_main.xml)

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>
    <LinearLayout
        android:layout_width = "match_parent"
        android:gravity = "center"
        android:layout_height = "wrap_content">
        <Button
            android:id = "@+id/passwordVisible"
            android:layout_width = "wrap_content"
            android:layout_height = "wrap_content"
            android:text = "Show"></Button>
        <Button
            android:id = "@+id/click"
            android:layout_width = "wrap_content"
            android:layout_height = "wrap_content"
            android:text = "Click"></Button>
    </LinearLayout>
</LinearLayout>

위 코드에는 두 개의 TextInputEditText(이메일, 비밀번호)와 두 개의 버튼이 포함되어 있습니다. Click 버튼을 누르면 입력된 데이터를 가져와 Toast로 화면에 출력하고, Show 버튼을 누르면 비밀번호가 표시 상태와 숨김 상태 사이에서 전환됩니다.

3단계: MainActivity.java 작성

src/MainActivity.java 파일에 아래 코드를 추가합니다.

package com.example.andy.myapplication;

import android.graphics.Point;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.PasswordTransformationMethod;
import android.view.TextureView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    Button PasswordVisble;
    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);
        PasswordVisble = findViewById(R.id.passwordVisible);
        PasswordVisble.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(password.getText().toString().isEmpty()){
                    password.setError("Please Enter Pass word");
                } else {
                    if(PasswordVisble.getText().toString().equals("Show")){
                    PasswordVisble.setText("Hide");
                    password.setTransformationMethod(null);
                    } else {
                        PasswordVisble.setText("Show");
                        password.setTransformationMethod(new PasswordTransformationMethod());
                    }
                }
            }
        });
        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");
                }
            }
        });
    }
}

핵심 로직 살펴보기

비밀번호의 표시 여부를 제어하는 핵심은 바로 PasswordTransformationMethod입니다. 실제 로직은 다음과 같습니다.

if(PasswordVisble.getText().toString().equals("Show")) {
    PasswordVisble.setText("Hide");
    password.setTransformationMethod(null);
} else {
    PasswordVisble.setText("Show");
    password.setTransformationMethod(new PasswordTransformationMethod());
}

위 코드의 동작 원리를 정리하면 다음과 같습니다.

  • 비밀번호 보이기: password.setTransformationMethod(null) — 변환 메서드를 null로 설정하여 입력값을 그대로 노출합니다.
  • 비밀번호 숨기기: password.setTransformationMethod(new PasswordTransformationMethod()) — 변환 메서드를 적용해 입력값을 점(•) 형태로 마스킹합니다.

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 Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run 아이콘을 클릭하세요. 목록에서 본인의 모바일 기기를 선택하면 앱이 실행됩니다.

안드로이드 앱에서 비밀번호 표시·숨김 전환 기능 구현하기 (단계별 가이드)

앱이 실행되면 초기 화면이 나타납니다. 이때 비밀번호를 입력하지 않은 상태에서 Show 버튼을 누르면 위 이미지처럼 오류 메시지가 표시됩니다.

안드로이드 앱에서 비밀번호 표시·숨김 전환 기능 구현하기 (단계별 가이드)

이제 비밀번호 입력란에 값을 입력하고 Show 버튼을 누르면, 아래 이미지처럼 비밀번호가 평문으로 표시됩니다.

안드로이드 앱에서 비밀번호 표시·숨김 전환 기능 구현하기 (단계별 가이드)

마무리

이처럼 PasswordTransformationMethod를 활용하면 별도의 외부 라이브러리 없이도 간단하게 비밀번호 표시/숨김 전환 기능을 구현할 수 있습니다. 참고로 최신 프로젝트라면 AndroidX(TextInputLayout, TextInputEditText)를 사용하고, Material Design 컴포넌트의 setEndIconMode(TextInputLayout.END_ICON_PASSWORD_TOGGLE)를 활용하면 눈 모양 아이콘으로 더욱 손쉽게 같은 기능을 구현할 수 있으니 함께 참고해 보시기 바랍니다.