Android文本输入框(EditText)输入密码时显示与隐藏
代码很简单,这里就不多废话了。
packagecc.c; importandroid.app.Activity; importandroid.os.Bundle; importandroid.text.Selection; importandroid.text.Spannable; importandroid.text.method.HideReturnsTransformationMethod; importandroid.text.method.PasswordTransformationMethod; importandroid.view.View; importandroid.view.View.OnClickListener; importandroid.widget.Button; importandroid.widget.EditText; /** *Demo描述: *文本输入框(EditText)切换密码的显示与隐藏 * *参考资料: *1http://developer.android.com/reference/android/text/method/HideReturnsTransformationMethod.html *2http://developer.android.com/reference/android/text/method/PasswordTransformationMethod.html * Thankyouverymuch */ publicclassMainActivityextendsActivity{ privateButtonmSwitchButton; privateEditTextmPasswordEditText; privatebooleanisHidden=true; @Override publicvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main); init(); } privatevoidinit(){ mSwitchButton=(Button)findViewById(R.id.button); mPasswordEditText=(EditText)findViewById(R.id.editText); mSwitchButton.setOnClickListener(newOnClickListener(){ @Override publicvoidonClick(Viewv){ if(isHidden){ //设置EditText文本为可见的 mPasswordEditText.setTransformationMethod(HideReturnsTransformationMethod.getInstance()); }else{ //设置EditText文本为隐藏的 mPasswordEditText.setTransformationMethod(PasswordTransformationMethod.getInstance()); } isHidden=!isHidden; mPasswordEditText.postInvalidate(); //切换后将EditText光标置于末尾 CharSequencecharSequence=mPasswordEditText.getText(); if(charSequenceinstanceofSpannable){ SpannablespanText=(Spannable)charSequence; Selection.setSelection(spanText,charSequence.length()); } } }); } }
有相同需求的小伙伴过来参考下吧,可以直接拿去使用。