您的位置:首页技术文章
文章详情页

Android 登录页面的实现代码(密码显示隐藏、EditText 图标切换、限制输入长度)

【字号: 日期:2022-09-23 08:29:23浏览:6作者:猪猪

效果演示

Android 登录页面的实现代码(密码显示隐藏、EditText 图标切换、限制输入长度)Android 登录页面的实现代码(密码显示隐藏、EditText 图标切换、限制输入长度)

密码显示与隐藏

方法一

if(status){ etPassword.setInputType(InputType.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_NORMAL);//显示文本 status = false;}else { etPassword.setInputType(InputType.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_PASSWORD);//隐藏文本 status = true;}etPassword.setSelection(etPassword.getText().toString().length());//光标调整到文本末端

方法二

if (status) { etPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());//显示文本 status = false;} else { etPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());//隐藏文本 status = true;}

EditText 图标切换

实现方法

//编辑框点击事件,取 icon 点击位置设置点击事件etPassword.setOnTouchListener(new View.OnTouchListener() {@Overridepublic boolean onTouch(View v, MotionEvent event) {// 长度为4的数组,分别表示左、右、上、下四个 iconDrawable drawable = etPassword.getCompoundDrawables()[2];if (drawable == null) //如果右边没有图片,不再处理return false;if (event.getAction() != MotionEvent.ACTION_UP)//如果不是按下事件,不再处理return false;if (event.getX() > etPassword.getWidth() - etPassword.getPaddingRight() - drawable.getIntrinsicWidth()) {//点击范围为右侧 icon 位置if (status) {status= false;//获取小眼睛图标Drawable iconDrawable = getResources().getDrawable(R.drawable.icon_eye_open);//设置新图标,分别对应左、上、右、下4个图标etPassword.setCompoundDrawablesWithIntrinsicBounds(null, null, iconDrawable, null);} else {status= true;Drawable iconDrawable = getResources().getDrawable(R.drawable.icon_eye_close);etPassword.setCompoundDrawablesWithIntrinsicBounds(null, null, iconDrawable, null);}}return false;}});

限制输入长度

方法一:以判断方式控制最大输入长度

private static final int MAX_INPUT_LENGTH = 50;//限制最大输入长度50etPassword.setFilters(new InputFilter[]{new InputFilter() {//通过过滤器进行限制 @Override public CharSequence filter(CharSequence charSequence, int start, int end, Spanned spanned, int dstart, int dend) { //charSequence 为输入内容(删除时为空),spanned 为输入前输入框内容 if ((!charSequence.toString().equals('')) && spanned.toString().length() >= MAX_INPUT_LENGTH) { //判断当前有内容输入(不为删除),且当前内容长度为最大长度,进行 Toast 提醒,且返回空 Toast.makeText(MyApplication.context, '最大输入长度为50', Toast.LENGTH_SHORT).show(); return '';//返回值为输入框增加内容,返回空不增加,默认返回 null } return null; }}});

方法二:以过滤器方式控制最大输入长度

etChange.setFilters(new InputFilter[]{new InputFilter() { @Override public CharSequence filter(CharSequence charSequence, int start, int end, Spanned spanned, int dstart, int dend) { if((!source.toString().equals('')) && dest.toString().length() >= MAX_INPUT_LENGTH){ Toast.makeText(MainActivity.this, '最大输入长度为50', Toast.LENGTH_SHORT).show(); } return null; }},new InputFilter.LengthFilter(MAX_INPUT_LENGTH)});//以过滤器方式控制最大输入长度

总结

到此这篇关于Android 登录页面的实现代码(密码显示隐藏、EditText 图标切换、限制输入长度)的文章就介绍到这了,更多相关Android 登录页面内容请搜索好吧啦网以前的文章或继续浏览下面的相关文章希望大家以后多多支持好吧啦网!

标签: Android
相关文章: