android/UI
[ Android ] Password 입력창에서 패스워드 숨기고 보이기
Soso Dev
2024. 8. 2. 18:30
반응형
안드로이드에서 비밀번호 입력 필드에서 입력된 비밀번호를 보이게 설정하는 방법에 대해 설명드리겠습니다. 일반적으로 비밀번호 입력 필드는 EditText
의 inputType
을 textPassword
로 설정하여 비밀번호를 감추는 형태로 사용됩니다. 그러나 사용자가 입력한 비밀번호를 잠시 동안 보이게 하려면 여러 가지 방법이 있습니다.
1. Toggle Button 사용하여 비밀번호 보이기/숨기기
사용자가 비밀번호를 보거나 숨길 수 있도록 Toggle Button
이나 CheckBox
를 사용하여 설정할 수 있습니다.
XML 레이아웃 파일
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<EditText
android:id="@+id/passwordEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:hint="Enter your password"/>
<CheckBox
android:id="@+id/showPasswordCheckBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Password"/>
</LinearLayout>
Java 코드
EditText passwordEditText = findViewById(R.id.passwordEditText);
CheckBox showPasswordCheckBox = findViewById(R.id.showPasswordCheckBox);
showPasswordCheckBox.setOnCheckedChangeListener((buttonView, isChecked) -> {
if (isChecked) {
// 비밀번호를 보이게 설정
passwordEditText.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
} else {
// 비밀번호를 다시 숨김
passwordEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
}
// 커서 위치를 설정
passwordEditText.setSelection(passwordEditText.length());
});
Kotlin 코드
val passwordEditText = findViewById<EditText>(R.id.passwordEditText)
val showPasswordCheckBox = findViewById<CheckBox>(R.id.showPasswordCheckBox)
showPasswordCheckBox.setOnCheckedChangeListener { _, isChecked ->
if (isChecked) {
// 비밀번호를 보이게 설정
passwordEditText.inputType = InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
} else {
// 비밀번호를 다시 숨김
passwordEditText.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
}
// 커서 위치를 설정
passwordEditText.setSelection(passwordEditText.text.length)
}
2. XML 속성을 통해 비밀번호 보이기 설정
XML에서 inputType
속성을 textVisiblePassword
로 설정하면 비밀번호가 기본적으로 보이게 됩니다.
<EditText
android:id="@+id/passwordEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textVisiblePassword"
android:hint="Enter your password"/>
위 예제처럼 CheckBox
또는 Toggle Button
을 사용하여 비밀번호를 보여주거나 숨기는 기능을 구현할 수 있습니다. 또한, 앱의 요구사항에 따라 XML 또는 코드에서 비밀번호 보이기 설정을 할 수 있습니다.
반응형