先贴代码
xml代码:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".PasswordActivity">
<EditText
android:id="@+id/edt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="password"
android:singleLine="true"
android:inputType="textPassword"
/>
<CheckBox
android:id="@+id/checkbox"
android:layout_gravity="end"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="查看密码"/>
</LinearLayout>
界面很简单,就是一个输入框和一个多选框。
如图:
点击多选框时,我们要把密文换成明文,取消勾选时要把明文换成密文。
大家可能第一想到inputType属性。
public class PasswordActivity extends AppCompatActivity {
public EditText edt;
public CheckBox checkbox;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_password);
edt=findViewById(R.id.edt);
checkbox=findViewById(R.id.checkbox);
checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
// edt.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
edt.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
}else {
edt.setInputType(InputType.TYPE_CLASS_TEXT);
}
}
});
}
}
然后运行就会发现,他只能把密文换成明文
转换成密文的那部分有误。
edt.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
进入InputType源码查看
/**
* Variation of {@link #TYPE_CLASS_NUMBER}: entering a numeric password.
* This was added in {@link android.os.Build.VERSION_CODES#HONEYCOMB}. An
* IME must target this API version or later to see this input type; if it
* doesn't, a request for this type will be dropped when passed
* through {@link android.view.inputmethod.EditorInfo#makeCompatible(int)
* EditorInfo.makeCompatible(int)}.
*/
public static final int TYPE_NUMBER_VARIATION_PASSWORD = 0x00000010;
一大段英文,简单翻译一下,就是这个标签是看密码输入类型的。
设置密码为密文状态的源码中没有。
所以不能通过setInputType函数实现这个需求,但是还好有别的函数。
public class PasswordActivity extends AppCompatActivity {
public EditText edt;
public CheckBox checkbox;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_password);
edt=findViewById(R.id.edt);
checkbox=findViewById(R.id.checkbox);
checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
edt.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
}else {
edt.setTransformationMethod(PasswordTransformationMethod.getInstance());
}
}
});
}
}
这也就可以实现明文密文切换了