Android 眼睛 顯示隱藏密碼(ImageView)

專注的阿熊發表於2022-07-05

package com.example.test2;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import android.text.method.HideReturnsTransformationMethod;

import android.text.method.PasswordTransformationMethod;

import android.view.View;

import android.widget.EditText;

import android.widget.ImageView;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

     private EditText password;

     private ImageView imageView;

     private boolean flag=true;

     private HideReturnsTransformationMethod method_show;

     @Override

     protected void onCreate(Bundle savedInstanceState) {

         super.onCreate(savedInstanceState);

         setContentView(R.layout.activity_main);

         password = findViewById(R.id.password);

         imageView = findViewById(R.id.img);

         imageView.setOnClickListener(this);

     }

     @Override

     public void onClick(View v) {

         switch (v.getId()){

             case R.id.img:

                 changeImage();

         }

     }

     private void changeImage() {

         // todo 跟單網gendan5.com 每次進入登陸時輸入的密碼都是隱藏的

         PasswordTransformationMethod methodHide=PasswordTransformationMethod.getInstance();

         password.setTransformationMethod(methodHide);

         if(flag){

imageView.setImageDrawable(this.getResources().getDrawable(R.drawable.eye1));

             flag=false;

             // todo 隱藏密碼

             PasswordTransformationMethod method_hide = PasswordTransformationMethod.getInstance();

             password.setTransformationMethod(method_hide);

         }

         else{

imageView.setImageDrawable(this.getResources().getDrawable(R.drawable.eye2));

             flag=true;

             // todo   顯示密碼

             method_show= HideReturnsTransformationMethod.getInstance();

             password.setTransformationMethod(method_show);

         }

         if (!password.getText().toString().trim().equals("")) {

             password.setSelection(password.getText().toString().trim().length());// 將游標移至文字末尾

         }

     }

}

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69946337/viewspace-2904361/,如需轉載,請註明出處,否則將追究法律責任。

相關文章