Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android文本輸入框(EditText)切換密碼的顯示與隱藏

Android文本輸入框(EditText)切換密碼的顯示與隱藏

編輯:關於Android編程

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如下:




    
    
    


  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved