欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2022-07-03 18:54:13
代码很简单,这里就不多废话了。 复制代码 代码如下: package cc.c; import android.app.activity; import andro...

代码很简单,这里就不多废话了。

复制代码 代码如下:

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
 *   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());
                }
 
            }
        });
    }
    
}

有相同需求的小伙伴过来参考下吧,可以直接拿去使用。