Android文本输入框(EditText)切换密码的显示与隐藏

MainActivity如下:
package cc.c;

import android.app.Activity;
import android.os.Bundle;
import android.text.Selection;
import android.text.Spannable;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
/**
 * Demo描述:
 * 文本输入框(EditText)切换密码的显示与隐藏
 * 
 * 参考资料:
 * 1 http://developer.android.com/reference/android/text/method/HideReturnsTransformationMethod.html
 * 2 http://developer.android.com/reference/android/text/method/PasswordTransformationMethod.html
 * 3 http://blog.csdn.net/dawanganban/article/details/23374187
 *   Thank you very much
 */
public class MainActivity extends Activity {
	private Button mSwitchButton;
	private EditText mPasswordEditText;
	private boolean isHidden=true;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        init();
    }
    private void init(){
    	mSwitchButton=(Button) findViewById(R.id.button);
    	mPasswordEditText=(EditText) findViewById(R.id.editText);
    	mSwitchButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (isHidden) {
					//设置EditText文本为可见的
					mPasswordEditText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
				} else {
					//设置EditText文本为隐藏的
					mPasswordEditText.setTransformationMethod(PasswordTransformationMethod.getInstance());
				}
				isHidden = !isHidden;
				mPasswordEditText.postInvalidate();
				//切换后将EditText光标置于末尾
				CharSequence charSequence = mPasswordEditText.getText();
				if (charSequence instanceof Spannable) {
					Spannable spanText = (Spannable) charSequence;
					Selection.setSelection(spanText, charSequence.length());
				}

			}
		});
    }
    
}

main.xml如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/editText"
        android:layout_width="160dip"
        android:layout_height="40dip"
        android:hint="请输入密码"
        android:inputType="textPassword"
    />
    
    <Button
        android:id="@+id/button"
        android:layout_width="160dip"
        android:layout_height="40dip"
        android:text="切换显示方式"
    />

</LinearLayout>


Android文本输入框(EditText)切换密码的显示与隐藏,,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。