English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Краткий анализ реализации поля ввода пароля для оплаты в Android

Сначала посмотрим на效果图

Метод реализации:

Элементы, превращающиеся в точки, это не TextView и EditText, а Imageview. Сначала создайте RelativeLayout, который содержит 6 Imageview и EditText (EditText должен перекрывать Imageview), и установите прозрачный фон для EditText.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="wrap_content">
 <LinearLayout
  android:layout_width="match_parent"
  android:layout_height="50dp"
  android:orientation="horizontal"
  android:background="@android:color/white">
  <ImageView
   android:id="@+id/item_password_iv1"
   android:layout_width="0dp"
   android:layout_height="match_parent"
   android:layout_weight="1"
   android:src="@mipmap/nopassword"/>
  <ImageView
   android:id="@+id/item_password_iv2"
   android:layout_width="0dp"
   android:layout_height="match_parent"
   android:layout_weight="1"
   android:src="@mipmap/nopassword"/>
  <ImageView
   android:id="@+id/item_password_iv3"
   android:layout_width="0dp"
   android:layout_height="match_parent"
   android:layout_weight="1"
   android:src="@mipmap/nopassword"/>
  <ImageView
   android:id="@+id/item_password_iv4"
   android:layout_width="0dp"
   android:layout_height="match_parent"
   android:layout_weight="1"
   android:src="@mipmap/nopassword"/>
  <ImageView
   android:id="@+id/item_password_iv5"
   android:layout_width="0dp"
   android:layout_height="match_parent"
   android:layout_weight="1"
   android:src="@mipmap/nopassword"/>
  <ImageView
   android:id="@+id/item_password_iv6"
   android:layout_width="0dp"
   android:layout_height="match_parent"
   android:layout_weight="1"
   android:src="@mipmap/nopassword"/>
 </LinearLayout>
 <EditText
  android:id="@+id/item_edittext"
  android:layout_width="match_parent"
  android:layout_height="50dp"
  android:background="@android:color/transparent"/>
</RelativeLayout>

Дефиниция пользовательского контрола ItemPasswordLayout, предназначенного для выполнения некоторых операций с макетом,重点 в том, чтобы удалить курсор EditText и отслеживать события ввода текста: при изменении текста поместить текст в StringBuffer и установить editText в ""; также отслеживать событие нажатия клавиши удаления клавиатуры, при нажатии на клавишу удаления удалить символ в StringBuffer по соответствующему положению.

/**
 * Логическая структура для поля ввода пароля
 * Создано Went_Gone 14 сентября 2016 года.
 */
public class ItemPasswordLayout extends RelativeLayout{
 private EditText editText;
 private ImageView[] imageViews; // использование массива для хранения фреймов пароля
 private StringBuffer stringBuffer = new StringBuffer(); // хранение символов пароля
 private int count = 6;
 private String strPassword; // парольная строка
 public ItemPasswordLayout(Context context) {
  this(context, null);
 }
 public ItemPasswordLayout(Context context, AttributeSet attrs) {
  this(context, attrs, 0);
 }
 public ItemPasswordLayout(Context context, AttributeSet attrs, int defStyleAttr) {
  super(context, attrs, defStyleAttr);
  imageViews = new ImageView[6];
  View view = View.inflate(context, R.layout.item_password,this);
  editText = (EditText) findViewById(R.id.item_edittext);
  imageViews[0] = (ImageView) findViewById(R.id.item_password_iv1);
  imageViews[1] = (ImageView) findViewById(R.id.item_password_iv2);
  imageViews[2] = (ImageView) findViewById(R.id.item_password_iv3);
  imageViews[3] = (ImageView) findViewById(R.id.item_password_iv4);
  imageViews[4] = (ImageView) findViewById(R.id.item_password_iv5);
  imageViews[5] = (ImageView) findViewById(R.id.item_password_iv6);
  editText.setCursorVisible(false); // скрывать курсор
  setListener();
 }
 private void setListener() {
  editText.addTextChangedListener(new TextWatcher() {
   @Override
   public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
   }
   @Override
   public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
   }
   @Override
   public void afterTextChanged(Editable editable) {
    //重点 如果字符不为""时才进行操作
    if (!editable.toString().equals("")) {
     if (stringBuffer.length()>5){
      //当密码长度大于5位时edittext置空
      editText.setText("");
      return;
     }
      //将文字添加到StringBuffer中
      stringBuffer.append(editable);
      editText.setText("");//添加后将EditText置空 造成没有文字输入的错局
      Log.e("TAG", "afterTextChanged: stringBuffer is "+stringBuffer);
      count = stringBuffer.length();//记录stringbuffer的长度
      strPassword = stringBuffer.toString();
      if (stringBuffer.length()==6){
       //文字长度位6 则调用完成输入的监听
       if (inputCompleteListener!=null){
        inputCompleteListener.inputComplete();
       }
      }
     }
     for (int i =0;i<stringBuffer.length();i++){
      imageViews[i].setImageResource(R.mipmap.ispassword);
     }
    }
   }
  });
  editText.setOnKeyListener(new OnKeyListener() {
   @Override
   public boolean onKey(View v, int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_DEL
      && event.getAction() == KeyEvent.ACTION_DOWN) {
//     Log.e("TAG", "afterTextChanged: stringBuffer is "+stringBuffer);
     if (onKeyDelete()) return true;
     return true;
    }
    return false;
   }
  });
 }
 public boolean onKeyDelete() {
  if (count==0){
   count = 6;
   return true;
  }
  if (stringBuffer.length()>0){
   //Удалить символ в соответствующем位置е
   stringBuffer.delete((count-1),count);
   count--;
   Log.e("TAG", "afterTextChanged: stringBuffer is "+stringBuffer);
   strPassword = stringBuffer.toString();
   imageViews[stringBuffer.length()].setImageResource(R.mipmap.nopassword);
  }
  return false;
 }
 @Override
 public boolean onKeyDown(int keyCode, KeyEvent event) {
  return super.onKeyDown(keyCode, event);
 }
 private InputCompleteListener inputCompleteListener;
 public void setInputCompleteListener(InputCompleteListener inputCompleteListener) {
  this.inputCompleteListener = inputCompleteListener;
 }
 public interface InputCompleteListener{
  void inputComplete();
 }
 public EditText getEditText() {
  return editText;
 }
 /**
  * Получить пароль
  * @return
  */
 public String getStrPassword() {
  return strPassword;
 }
 public void setContent(String content){
  editText.setText(content);
 }
}

Далее достаточно просто вызвать Activity.

в xml中表示

 <com.example.went_gone.demo.view.ItemPasswordLayout>
  android:id="@+id/act_zhifubao_IPLayout"
  android:layout_width="match_parent"
  android:layout_height="wrap_content">
 </com.example.went_gone.demo.view.ItemPasswordLayout>

В Activity вызывается

 itemPasswordLayout = (ItemPasswordLayout) findViewById(R.id.act_zhifubao_IPLayout);
  itemPasswordLayout.setInputCompleteListener(new ItemPasswordLayout.InputCompleteListener() {
   @Override
   public void inputComplete() {
    Toast.makeText(ZhifubaoActivity.this, "Пароль: " + itemPasswordLayout.getStrPassword(), Toast.LENGTH_SHORT).show();
   }
  });

Обобщение

Хорошо, содержимое статьи заканчивается здесь. Это все, что нужно. Не слишком просто? Надеюсь, эта статья поможет вам в изучении или работе. Если у вас есть вопросы, вы можете оставить комментарий для обсуждения.

Заявление: содержимое этой статьи взято из Интернета, авторские права принадлежат соответствующему автору. Контент предоставлен пользователями Интернета, загружен пользователями самостоятельно, сайт не имеет права собственности, не был отредактирован вручную и не несет ответственности за соответствующие юридические вопросы. Если вы обнаружите содержимое,涉嫌侵犯版权, пожалуйста, отправьте письмо по адресу: notice#oldtoolbag.com (во время отправки письма замените # на @) для сообщения о нарушении,并提供 соответствующие доказательства. При обнаружении факта нарушения, сайт немедленно удалят涉嫌侵权的内容。

Рекомендуем также