【发布时间】:2011-04-10 18:58:57
【问题描述】:
有没有一种巧妙的方法让用户在 android EditText 中在隐藏和查看密码之间切换? 许多基于 PC 的应用程序允许用户执行此操作。
【问题讨论】:
有没有一种巧妙的方法让用户在 android EditText 中在隐藏和查看密码之间切换? 许多基于 PC 的应用程序允许用户执行此操作。
【问题讨论】:
使用下面的代码
val hidePasswordMethod = PasswordTransformationMethod()
showOrHidePasswordButton.setOnClickListener {
passwordEditText.apply {
transformationMethod =
if (transformationMethod is PasswordTransformationMethod)
null //shows password
else
hidePasswordMethod //hides password
}
}
并确保将其添加到布局中的密码编辑文本中
android:inputType="textPassword"
【讨论】:
如果您想要一个简单的解决方案,您可以使用 Android 的 EditText 扩展,请访问此链接了解更多信息:https://github.com/scottyab/showhidepasswordedittext
将此添加到您的 build.gradle: 实现 'com.github.scottyab:showhidepasswordedittext:0.8'
然后在您的 XML 文件中更改您的 EditText。
来自: 收件人: 就是这样。 注意:您在 XML 设计中看不到它,请尝试在您的模拟器或物理设备中运行它。
【讨论】:
input_layout.isPasswordVisibilityToggleEnabled = true 似乎已被弃用。就我而言,我在 Kotlin 中就是这样做的:
input_edit_text.inputType = TYPE_CLASS_TEXT or TYPE_TEXT_VARIATION_PASSWORD
input_layout.endIconMode = END_ICON_PASSWORD_TOGGLE
其中 input_edit_text 是 com.google.android.material.textfield.TextInputEditText 并且 input_layout 是 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(...)
【讨论】:
if (inputPassword.getTransformationMethod() == PasswordTransformationMethod.getInstance()) {
//password is visible
inputPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
}
else if(inputPassword.getTransformationMethod() == HideReturnsTransformationMethod.getInstance()) {
//password is hidden
inputPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
}
【讨论】:
只需在 Xml 文件中创建一个复选框
然后简单的用java代码写这个函数
checkbox = findViewById(R.id.checkbox);
checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked){
if (isChecked) {
password.setTransformationMethod(null);
}
else{
password.setTransformationMethod(new PasswordTransformationMethod());
}
}
});
【讨论】: