【问题标题】:Define a value to EditText为 EditText 定义一个值
【发布时间】:2019-01-30 23:44:06
【问题描述】:

我正在尝试使用 EditText 制作一个 Activity,它只能接受我在高级中以编程方式定义的值 - 类似于密码,如单词或代码编号 - 以便用户无法访问下一个活动,如果他没有输入正确的密码

有没有人知道如何制作这样的东西?我必须使用 TextWatcher 吗?如果是,如何?

谢谢!

【问题讨论】:

  • android:digits="enter_your_characters_here" 在你的 xml 布局中应该做你想做的事。

标签: android android-activity android-edittext password-protection textwatcher


【解决方案1】:

使用这个。

If (edittext.getText().toString()==myPreProgrammedString){
   start next activity
}
else{
   show warning wrong password
}

通常您会在登录按钮的 onClick 方法中放置类似的内容。但是我在 textwatchers afterTextChanged 方法中使用了类似的东西来检查输入的文本是否在列表中,然后启用 OK 按钮。

顺便说一句:在应用程序中硬编码密码从来都不是好习惯。

【讨论】:

  • 谢谢,它有效!如果我可能会问,我怎样才能储存密码呢?
  • 让用户自己思考密码、散列并将其存储在诸如 firebase 之类的东西中的最佳方式。使用硬编码密码,每个用户都有相同的密码,并且重新设计您的应用程序会为未经授权的人提供密码。就像我说的,不是很安全。
  • 其实我做的是一个游戏,在玩家输入密码的Activity之前,会提示输入正确的密码。他必须猜,所以只有一个可能的答案!就像当你得到一个谜语并试图猜测答案时一样。
  • 因此并不是真正的安全风险,只有作弊者才会破解该应用程序。那么硬编码的字符串是可以接受的。
【解决方案2】:

使用正则表达式(regex)来定义您的密码格式。正则表达式密码示例:

^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])(?=\S+$).{8,}$
^                 # start-of-string
(?=.*[0-9])       # a digit must occur at least once
(?=.*[a-z])       # a lower case letter must occur at least once
(?=.*[A-Z])       # an upper case letter must occur at least once
(?=.*[@#$%^&+=])  # a special character must occur at least once
(?=\S+$)          # no whitespace allowed in the entire string
.{8,}             # anything, at least eight places though
$ 

            # end-of-string

将 TextWatch 添加到您的 EditText 以观察您输入时的文本变化

yourEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
               Pattern PASSWORD_PATTERN = Pattern.compile("Your pattern");

                if (PASSWORD_PATTERN.matcher(s.toString()).matches()) { 
                    //Password is valid, move to new activity
                }
            }
        });

正则表达式很简单!

【讨论】:

  • 我不认为艾玛是兄弟:)。
猜你喜欢
  • 1970-01-01
  • 2016-08-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-08
  • 1970-01-01
  • 1970-01-01
  • 2011-11-11
  • 2015-02-24
相关资源
最近更新 更多