비밀번호 숨기기와 보기를 전환하는 방법
안드로이드 EditText에서 비밀번호 숨기기와 보기 사이를 전환할 수 있는 현명한 방법이 있습니까?많은 PC 기반 앱들이 사용자가 이것을 할 수 있게 해줍니다.
Support Library v24.2.0 이후로 달성하기가 매우 쉽습니다.
당신이 해야 할 일은 바로 다음과 같습니다.
종속성에 디자인 라이브러리 추가
dependencies { compile "com.android.support:design:24.2.0" }
사용하다
TextInputEditText
함께TextInputLayout
<android.support.design.widget.TextInputLayout android:id="@+id/etPasswordLayout" android:layout_width="match_parent" android:layout_height="wrap_content" app:passwordToggleEnabled="true" android:layout_marginBottom="@dimen/login_spacing_bottom"> <android.support.design.widget.TextInputEditText android:id="@+id/etPassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/fragment_login_password_hint" android:inputType="textPassword"/> </android.support.design.widget.TextInputLayout>
passwordToggleEnabled
Attribute가 할 수 있을 것입니다!
에서 하는 을 에서 을 하는 )
xmlns:app="http://schemas.android.com/apk/res-auto"
다음을 사용하여 암호 토글을 사용자 지정할 수 있습니다.
app:passwordToggleDrawable
할 수 있는 . -호력글로할다수성다수할w로nsoe글ee력t호 .
app:passwordToggleTint
토글에 . -호력에할다성다할에n성ro력ee호tsd .
app:passwordToggleTintMode
tint -는데는딩드를드eyogd는데edk경t .
TextInputLayout 설명서에서 자세한 내용을 확인합니다.
Android X의 경우
교체
android.support.design.widget.TextInputLayout
와 함께com.google.android.material.textfield.TextInputLayout
교체
android.support.design.widget.TextInputEditText
와 함께com.google.android.material.textfield.TextInputEditText
TextView의 속성을 동적으로 변경할 수 있습니다. XML을 과 같이 .android:password
됩니다. true로 설정하면 됩니다. true로 설정하면 가 표시됩니다. 텍스트는 false로 설정하면 점이 표시됩니다.
method setTransformationMethod를 사용하면 코드에서 이 속성을 변경할 수 있습니다. (Disclaimer:뷰가 표시된 후에도 여전히 방법이 작동하는지 테스트하지 않았습니다.만약 당신이 그것과 관련된 문제가 생기면 제게 의견을 남겨주세요.)
전체 샘플 코드는
yourTextView.setTransformationMethod(new PasswordTransformationMethod());
비밀번호를 숨깁니다.암호를 표시하려면 기존 변환 방법 중 하나를 설정하거나 입력 텍스트를 사용하지 않는 빈 변환 방법을 구현할 수 있습니다.
yourTextView.setTransformationMethod(new DoNothingTransformation());
암호 대신 점을 표시하려면 암호 변환 방법을 설정합니다.
yourEditText.setTransformationMethod(new PasswordTransformationMethod());
물론 xml 레이아웃의 편집 텍스트 요소에서 기본적으로 설정할 수 있습니다.
android:password
판독 가능한 암호를 다시 표시하려면 null을 변환 방법으로 전달합니다.
yourEditText.setTransformationMethod(null);
표시 방법:
editText.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
숨기기:
editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
각각의 커서가 재설정되면 다음과 같이 됩니다.
editText.setSelection(editText.length());
사용가능
아래에 주어진 예시가 있습니다.
<android.support.design.widget.TextInputLayout
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:passwordToggleEnabled="true"
android:textColorHint="@color/colorhint"
android:textColor="@color/colortext">
저도 같은 이슈가 있었는데 구현하기가 매우 쉽습니다.
텍스트 편집 필드를 (com.google.android.material.text) 필드에 래핑하기만 하면 됩니다.TextInputLayout) 및 추가(앱:passwordToggleEnabled="true").
이렇게 하면 텍스트 편집 필드에 눈이 표시되고 다시 클릭하면 암호가 나타나고 사라집니다.
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColorHint="#B9B8B8"
app:passwordToggleEnabled="true">
<EditText
android:id="@+id/register_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="24dp"
android:layout_marginRight="44dp"
android:backgroundTint="#BEBEBE"
android:hint="Password"
android:inputType="textPassword"
android:padding="16dp"
android:textSize="18sp" />
</com.google.android.material.textfield.TextInputLayout>
확인란을 사용하고 그에 따라 입력 유형을 변경합니다.
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int start,end;
Log.i("inside checkbox chnge",""+isChecked);
if(!isChecked){
start=passWordEditText.getSelectionStart();
end=passWordEditText.getSelectionEnd();
passWordEditText.setTransformationMethod(new PasswordTransformationMethod());;
passWordEditText.setSelection(start,end);
}else{
start=passWordEditText.getSelectionStart();
end=passWordEditText.getSelectionEnd();
passWordEditText.setTransformationMethod(null);
passWordEditText.setSelection(start,end);
}
}
처음에는 이미지 벡터 자산 가시성이 로드된 화면입니다.
클릭하면 이 이미지 가시성 꺼짐으로 바뀝니다.
위의 암호 스위치에 대한 코드(xml 코드)
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/laypass"
android:layout_width="330dp"
android:layout_height="50dp"
android:layout_marginTop="24dp"
app:layout_constraintEnd_toEndOf="@+id/editText3"
app:layout_constraintStart_toStartOf="@+id/editText3"
app:layout_constraintTop_toBottomOf="@+id/editText3">
<EditText
android:id="@+id/edit_password"
style="@style/EditTextTheme"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/round"
android:drawableLeft="@drawable/ic_password"
android:drawablePadding="10dp"
android:ems="10"
android:hint="Password"
android:inputType="textPassword"
android:paddingLeft="10dp"
android:paddingRight="15dp"
android:textColor="@color/cyan92a6"
android:textColorHint="@color/cyan92a6"
android:textCursorDrawable="@null"
android:textSize="18sp"
/>
<ImageView
android:id="@+id/show_pass_btn"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginEnd="8dp"
android:alpha=".5"
android:onClick="ShowHidePass"
android:padding="5dp"
android:src="@drawable/ic_visibility"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="@+id/laypass"
app:layout_constraintTop_toTopOf="@+id/edit_password" />
</androidx.constraintlayout.widget.ConstraintLayout>
버튼 조작을 위한 Java 코드
public void ShowHidePass(View view) {
if(view.getId()==R.id.show_pass_btn){
if(edit_password.getTransformationMethod().equals(PasswordTransformationMethod.getInstance())){
((ImageView)(view)).setImageResource(R.drawable.ic_visibility_off);
//Show Password
edit_password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
}
else{
((ImageView)(view)).setImageResource(R.drawable.ic_visibility);
//Hide Password
edit_password.setTransformationMethod(PasswordTransformationMethod.getInstance());
}
}
}
private boolean isPasswordVisible;
private TextInputEditText firstEditText;
...
firstEditText = findViewById(R.id.et_first);
...
private void togglePassVisability() {
if (isPasswordVisible) {
String pass = firstEditText.getText().toString();
firstEditText.setTransformationMethod(PasswordTransformationMethod.getInstance());
firstEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
firstEditText.setText(pass);
firstEditText.setSelection(pass.length());
} else {
String pass = firstEditText.getText().toString();
firstEditText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
firstEditText.setInputType(InputType.TYPE_CLASS_TEXT);
firstEditText.setText(pass);
firstEditText.setSelection(pass.length());
}
isPasswordVisible= !isPasswordVisible;
}
제 일입니다.이것은 당신에게 확실히 도움이 될 것입니다.
showpass.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(!isChecked){
// show password
password_login.setTransformationMethod(PasswordTransformationMethod.getInstance());
Log.i("checker", "true");
}
else{
Log.i("checker", "false");
// hide password
password_login.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
}
}
});
나는 이 질문에 대답하고 싶어요 심지어 좋은 답변들이 있기도 하지만,
설명서에 따르면 변환 방법은 우리의 임무를 수행합니다.
변환방법
텍스트 보기에서는 변환 방법을 사용하여 암호의 문자를 점으로 바꾸거나 새 줄 문자가 한 줄 텍스트 필드에 줄 바꿈을 방지하는 등의 작업을 수행합니다.
Butter knife를 사용하지만 사용자가 show password를 확인하면 동일합니다.
@OnCheckedChanged(R.id.showpass)
public void onChecked(boolean checked){
if(checked){
et_password.setTransformationMethod(null);
}else {
et_password.setTransformationMethod(new PasswordTransformationMethod());
}
// cursor reset his position so we need set position to the end of text
et_password.setSelection(et_password.getText().length());
}
블록에 자체 포함된 몇 줄만으로 ShowPassword / HidePassword 코드를 추가할 수 있습니다.
protected void onCreate(Bundle savedInstanceState) {
...
etPassword = (EditText)findViewById(R.id.password);
etPassword.setTransformationMethod(new PasswordTransformationMethod()); // Hide password initially
checkBoxShowPwd = (CheckBox)findViewById(R.id.checkBoxShowPwd);
checkBoxShowPwd.setText(getString(R.string.label_show_password)); // Hide initially, but prompting "Show Password"
checkBoxShowPwd.setOnCheckedChangeListener( new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
if (isChecked) {
etPassword.setTransformationMethod(null); // Show password when box checked
checkBoxShowPwd.setText(getString(R.string.label_hide_password)); // Prompting "Hide Password"
} else {
etPassword.setTransformationMethod(new PasswordTransformationMethod()); // Hide password when box not checked
checkBoxShowPwd.setText(getString(R.string.label_show_password)); // Prompting "Show Password"
}
}
} );
...
매우 간단한 형태로:
private fun updatePasswordVisibility(editText: AppCompatEditText) {
if (editText.transformationMethod is PasswordTransformationMethod) {
editText.transformationMethod = null
} else {
editText.transformationMethod = PasswordTransformationMethod()
}
editText.setSelection(editText.length())
}
도움이 되길 바랍니다.
private int passwordNotVisible=1;
@Override
protected void onCreate(Bundle savedInstanceState) {
showPassword = (ImageView) findViewById(R.id.show_password);
showPassword.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EditText paswword = (EditText) findViewById(R.id.Password);
if (passwordNotVisible == 1) {
paswword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
passwordNotVisible = 0;
} else {
paswword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
passwordNotVisible = 1;
}
paswword.setSelection(paswword.length());
}
});
}
github에서 https://github.com/maksim88/PasswordEditText 프로젝트를 시도해 보세요.그것을 이용해서 자바 코드를 바꿀 필요도 없습니다.저스트 체인지
텍스트 편집
꼬리표로 삼다
com.maksim88.passwordedtext.암호 텍스트 편집
XML 파일에 저장할 수 있습니다.
아래 코드를 사용하여 비밀번호를 SHOW/HIDE할 수 있습니다.
XML 코드:
<EditText
android:id="@+id/etPassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="21dp"
android:layout_marginTop="14dp"
android:ems="10"
android:inputType="textPassword" >
<requestFocus />
</EditText>
<CheckBox
android:id="@+id/cbShowPwd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/etPassword"
android:layout_below="@+id/etPassword"
android:text="@string/show_pwd" />
자바 코드:
EditText mEtPwd;
CheckBox mCbShowPwd;
mEtPwd = (EditText) findViewById(R.id.etPassword);
mCbShowPwd = (CheckBox) findViewById(R.id.cbShowPwd);
mCbShowPwd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// checkbox status is changed from uncheck to checked.
if (!isChecked) {
// show password
mEtPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
} else {
// hide password
mEtPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
}
}
});
시도해 보기:
먼저 플래그를 다음과 같이 전역으로 정의합니다.
private boolean isShowPassword = false;
그리고 청취자가 표시 및 숨김 비밀번호 버튼을 조작하도록 설정합니다.
imgPassword.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isShowPassword) {
etPassword.setTransformationMethod(new PasswordTransformationMethod());
imgPassword.setImageDrawable(getResources().getDrawable(R.drawable.ic_eye_hide));
isShowPassword = false;
}else{
etPassword.setTransformationMethod(null);
imgPassword.setImageDrawable(getResources().getDrawable(R.drawable.ic_eye_show));
isShowPassword = true;
}
}
});
비밀번호 표시 및 숨기기 편집_텍스트(체크 박스 포함)
XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:inputType="textPassword"
android:id="@+id/edtPass"
android:textSize="20dp"
android:hint="password"
android:padding="20dp"
android:background="#efeaea"
android:layout_width="match_parent"
android:layout_margin="20dp"
android:layout_height="wrap_content" />
<CheckBox
android:background="#ff4"
android:layout_centerInParent="true"
android:textSize="25dp"
android:text="show password"
android:layout_below="@id/edtPass"
android:id="@+id/showPassword"
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:gravity="top|right"
android:layout_height="wrap_content" />
</RelativeLayout>
자바 코드
package com.example.root.sql2;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatCheckBox;
import android.support.v7.widget.Toolbar;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
public class password extends AppCompatActivity {
EditText password;
CheckBox show_hide_password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hide);
findViewById();
show_hide_pass();
}//end onCreate
public void show_hide_pass(){
show_hide_password.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (!b){
// hide password
password.setTransformationMethod(PasswordTransformationMethod.getInstance());
}else{
// show password
password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
}
}
});
} // end show_hide_pass
public void findViewById(){ // find ids ui and
password = (EditText) findViewById(R.id.edtPass);
show_hide_password = (CheckBox) findViewById(R.id.showPassword);
}//end findViewById
}// end class
setTransformationMethod로 해보셨습니까?TextView에서 상속되며 변환 메서드를 매개 변수로 사용합니다.
변환 방법에 대한 자세한 내용은 여기에서 확인할 수 있습니다.
캐릭터 교체와 같은 멋진 기능도 있습니다.
제가 한 일은
- 편집 텍스트 보기 및 일반 텍스트 보기 만들기
- 제약조건 레이아웃(Facebook 앱 로그인 화면과 같이)을 이용하여 서로 겹치도록 합니다.
- onClickListener를 일반 텍스트 뷰에 부착하여 편집 텍스트 뷰의 입력 유형을 적절히 변경합니다(Visible / Non-visible).
더 자세한 단계와 설명은 이 비디오를 확인하실 수 있습니다. https://youtu.be/md3eVaRzdIM
도움이 되길 바랍니다 :)
다음은 TextInputEdit을 사용하지 않는 솔루션입니다.텍스트 및 변환 방법.
XML
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
style="@style/FormLabel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/username" />
<EditText
android:id="@+id/loginUsername"
style="@style/EditTextStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableLeft="@drawable/ic_person_outline_black_24dp"
android:drawableStart="@drawable/ic_person_outline_black_24dp"
android:inputType="textEmailAddress"
android:textColor="@color/black" />
<TextView
style="@style/FormLabel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="@string/password" />
<EditText
android:id="@+id/loginPassword"
style="@style/EditTextStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableEnd="@drawable/ic_visibility_off_black_24dp"
android:drawableLeft="@drawable/ic_lock_outline_black_24dp"
android:drawableRight="@drawable/ic_visibility_off_black_24dp"
android:drawableStart="@drawable/ic_lock_outline_black_24dp"
android:inputType="textPassword"
android:textColor="@color/black" />
</LinearLayout>
자바 코드
boolean VISIBLE_PASSWORD = false; //declare as global variable befor onCreate()
loginPassword = (EditText)findViewById(R.id.loginPassword);
loginPassword.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
final int DRAWABLE_LEFT = 0;
final int DRAWABLE_TOP = 1;
final int DRAWABLE_RIGHT = 2;
final int DRAWABLE_BOTTOM = 3;
if (event.getAction() == MotionEvent.ACTION_UP) {
if (event.getRawX() >= (loginPassword.getRight() - loginPassword.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) {
// your action here
//Helper.toast(LoginActivity.this, "Toggle visibility");
if (VISIBLE_PASSWORD) {
VISIBLE_PASSWORD = false;
loginPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
loginPassword.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_lock_outline_black_24dp, 0, R.drawable.ic_visibility_off_black_24dp, 0);
} else {
VISIBLE_PASSWORD = true;
loginPassword.setInputType(InputType.TYPE_CLASS_TEXT);
loginPassword.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_lock_outline_black_24dp, 0, R.drawable.ic_visibility_black_24dp, 0);
}
return false;
}
}
return false;
}
});
이 출처에 따르면 프로젝트를 AndroidX로 마이그레이션한 경우 다음을 대체할 수 있습니다.
compile "com.android.support:design:24.2.0"
와 함께
implementation "com.google.android.material:material:1.0.0"
그러면 아래의 코드를 레이아웃 파일에 넣기만 하면 됩니다.
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:passwordToggleEnabled="true"
android:hint="@string/hint_text">
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</com.google.android.material.textfield.TextInputLayout>
소재에 대한 더 많은 정보TextInputLayout
여기서 찾을 수 있습니다.
이 소스를 사용하려면 Android Support Library에서 Android X로 마이그레이션하는 것이 좋습니다.
Android X는 Android 팀이 Jetpack 내에서 라이브러리를 개발, 테스트, 패키지, 버전 및 릴리스하는 데 사용하는 오픈 소스 프로젝트입니다.
AndroidX는 원래의 Android Support Library를 크게 개선한 것입니다.지원 라이브러리와 마찬가지로 Android X는 Android OS와 별도로 제공되며 Android 릴리스 전반에 걸쳐 하위 호환성을 제공합니다.AndroidX는 기능 패리티와 새 라이브러리를 제공함으로써 지원 라이브러리를 완전히 대체합니다.또한 안드로이드 X는 다음과 같은 기능을 포함합니다.
AndroidX의 모든 패키지는 Androidx 문자열로 시작하는 일관된 네임스페이스에 저장됩니다.지원 라이브러리 패키지가 해당하는 Androidx에 매핑되었습니다.* 꾸러미들모든 이전 클래스와 빌드 아티팩트를 새 클래스에 전체 매핑하려면 Package Refactoring 페이지를 참조하십시오.
지원 라이브러리와 달리 안드로이드X 패키지는 별도로 유지 및 업데이트됩니다.Androidx 패키지는 버전 1.0.0부터 엄격한 Semantic Versioning을 사용합니다.프로젝트에서 AndroidX 라이브러리를 독립적으로 업데이트할 수 있습니다.
모든 새로운 지원 라이브러리 개발은 AndroidX 라이브러리에서 이루어집니다.여기에는 원래의 지원 라이브러리 아티팩트를 유지 관리하고 새로운 Jetpack 구성 요소를 도입하는 작업이 포함됩니다.
좋은 해결책.버튼을 설정한 다음 다음 코드를 사용합니다.
public void showPassword(View v)
{
TextView showHideBtnText = (TextView) findViewById(R.id.textView1);
if(showHideBtnText.getText().toString().equals("Show Password")){
password.setTransformationMethod(null);
showHideBtnText.setText("Hide");
} else{
password.setTransformationMethod(new PasswordTransformationMethod());
showHideBtnText.setText("Show Password");
}
}
1 - 선택기 파일 "show_password_selector.xml" 만들기
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/pwd_hide"
android:state_selected="true"/>
<item android:drawable="@drawable/pwd_show"
android:state_selected="false" />
</selector>
2 - 이미지 보기에 "show_password_selector" 파일을 입력합니다.
<ImageView
android:id="@+id/iv_pwd"
android:layout_width="@dimen/_35sdp"
android:layout_height="@dimen/_25sdp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="@dimen/_15sdp"
android:src="@drawable/show_password_selector" />
3 - java 파일에 code 아래에 입력합니다.
iv_new_pwd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (iv_new_pwd.isSelected()) {
iv_new_pwd.setSelected(false);
Log.d("mytag", "in case 1");
edt_new_pwd.setInputType(InputType.TYPE_CLASS_TEXT);
} else {
Log.d("mytag", "in case 1");
iv_new_pwd.setSelected(true);
edt_new_pwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
}
}
});
현재 텍스트가 이미 점으로 표시되어 있는지 물어보아야 합니다. PasswordTransformationMethod.getInstance() 함수를 사용하면 그렇게 할 수 있습니다.
이것이 코틀린에서의 나의 기능입니다.
fun hideAndShowPassword(editText: EditText, indicator: ImageView) {
if (editText.transformationMethod == PasswordTransformationMethod.getInstance()) {
editText.transformationMethod = HideReturnsTransformationMethod.getInstance()
indicator.setImageDrawable(
ContextCompat.getDrawable(
editText.context,
R.drawable.eye
)
)
indicator.imageTintList =
ContextCompat.getColorStateList(editText.context, R.color.colorTintIcons)
} else {
editText.transformationMethod = PasswordTransformationMethod.getInstance()
indicator.setImageDrawable(
ContextCompat.getDrawable(
editText.context,
R.drawable.eye_off
)
)
indicator.imageTintList =
ContextCompat.getColorStateList(editText.context, R.color.colorTintIcons)
}
editText.setSelection(editText.text.length)
}
아래코드를사용
val hidePasswordMethod = PasswordTransformationMethod()
showOrHidePasswordButton.setOnClickListener {
passwordEditText.apply {
transformationMethod =
if (transformationMethod is PasswordTransformationMethod)
null //shows password
else
hidePasswordMethod //hides password
}
}
그리고 이것을 당신의 비밀번호에 추가해야합니다 레이아웃의 텍스트 편집
android:inputType="textPassword"
는 것 같습니다.input_layout.isPasswordVisibilityToggleEnabled = true
사용되지 않습니다.그리고 제 경우에는 코틀린에서 그렇게 했습니다.
input_edit_text.inputType = TYPE_CLASS_TEXT or TYPE_TEXT_VARIATION_PASSWORD
input_layout.endIconMode = END_ICON_PASSWORD_TOGGLE
는 ① 입력_edit_text입니다.com.google.android.material.textfield.TextInputEditText
input_limit 입니다.com.google.android.material.textfield.TextInputLayout
물론 다음 사항도 함께 가져와야 합니다.
import android.text.InputType.TYPE_CLASS_TEXT
import android.text.InputType.TYPE_TEXT_VARIATION_PASSWORD
import com.google.android.material.textfield.TextInputLayout.END_ICON_PASSWORD_TOGGLE
마이는 다음과 같이 제공된 메서드로 아이콘을 사용자 지정할 수 있습니다.
input_layout.endIconDrawable = ...
input_layout.setEndIconOnClickListener { }
input_layout.setEndIconOnLongClickListener(...)
툴로 사용할 버튼에 연결된 OnClickListener()를 사용했습니다.
private EditText email_et, contraseña_et;
protected void onCreate(Bundle savedInstanceState) {
....
contraseña_et = (EditText) findViewById(R.id.contraseña_et);
....
vercontra_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int inputType = contraseña_et.getInputType();
if (inputType == 129){
contraseña_et.setInputType(1);
} else {
contraseña_et.setInputType(129);
}
contraseña_et.setSelection(contraseña_et.getText().length());
}
});
문서를 읽어보니 int 값이 다른 것 같아서 정확한 값을 찾기 위해 디버그를 해봤습니다. 작동이 아주 좋고 이런 식으로 조금 더 쉽습니다.
[그런데 스페인어로 콘트라세냐는 비밀번호입니다.]
you can use this
private fun showPasswordSwitch(checked: Boolean) {
registerBinding.registerActivityEditTextPassword.also {
// Password hide-show
it.inputType =
if (checked) TEXT_PASSWORD_SHOW else TEXT_PASSWORD_HIDE
}
}
const val TEXT_PASSWORD_SHOW = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
const val TEXT_PASSWORD_HIDE = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
XML에서는 이렇게 합니다.
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:orientation="vertical"
>
<RelativeLayout
android:id="@+id/REFReLayTellFriend"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<EditText
android:id="@+id/etpass1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@android:color/transparent"
android:bottomLeftRadius="10dp"
android:bottomRightRadius="50dp"
android:fontFamily="@font/frutiger"
android:gravity="start"
android:inputType="textPassword"
android:hint="@string/regpass_pass1"
android:padding="20dp"
android:paddingBottom="10dp"
android:textColor="#000000"
android:textColorHint="#d3d3d3"
android:textSize="14sp"
android:topLeftRadius="10dp"
android:topRightRadius="10dp"/>
<ImageButton
android:id="@+id/imgshowhide1"
android:layout_width="40dp"
android:layout_height="20dp"
android:layout_marginTop="20dp"
android:layout_marginRight="10dp"
android:background="@drawable/showpass"
android:layout_alignRight="@+id/etpass1"/>
</RelativeLayout>
boolean show=true;
//on image click inside password do this
if(show){
imgshowhide2.setBackgroundResource(0);
imgshowhide2.setBackgroundResource(R.drawable.hide);
etpass2.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
etpass2.setSelection(etpass2.getText().length());
show=false;
}else{
imgshowhide2.setBackgroundResource(0);
imgshowhide2.setBackgroundResource(R.drawable.showpass);
//etpass1.setInputType(InputType.TYPE_TEXT);
etpass2.setInputType(InputType.TYPE_CLASS_TEXT |
InputType.TYPE_TEXT_VARIATION_PASSWORD);
etpass2.setSelection(etpass2.getText().length());
show=true;
}
언급URL : https://stackoverflow.com/questions/3685790/how-to-switch-between-hide-and-view-password
'it-source' 카테고리의 다른 글
SQL Server에서 변수를 선언하고 동일한 저장 프로시저에서 사용하는 방법 (0) | 2023.09.08 |
---|---|
PowerShell로 한 번에 컴퓨터 이름 변경 및 도메인 가입 (0) | 2023.09.08 |
Angular2 \ Typcript에서 문자열을 날짜로 변환하는 방법? (0) | 2023.09.08 |
장고에서 X 편집 가능한 인라인 편집 - CSRF 보호를 받는 방법은? (0) | 2023.09.08 |
자바스크립트에서 단어를 자르지 않고 문자열을 단축합니다. (0) | 2023.09.08 |