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 登錄頁面內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章:
