android 監聽EditText輸入字符長度

jopen 10年前發布 | 59K 次閱讀 Android Android開發 移動開發

項目當中的要求很多,最近遇到了一些要求,在Dialog上用戶輸入密碼,當密碼位數達到6位并且自動判斷密碼是否正確,如果正確Dialog自動消失,跳轉其他界面。 看似很艱難,其實只要你知道有這樣一個監聽就簡單多了。這個監聽就是addTextChangedListener(EditText s).

    public class EditTextActivity extends Activity implements OnClickListener{
private EditText adb_password;
public boolean change = false;
private LinearLayout adb_lin2;
private Button button1;
private Button button2;

    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.kvadb);  

        adb_password = (EditText) findViewById(R.id.adb_password);  
        adb_lin2 = (LinearLayout) findViewById(R.id.adb_lin2);  
        button1 = (Button) findViewById(R.id.button1);  
        button2 = (Button) findViewById(R.id.button2);  

        button1.setOnClickListener(this);  
        button2.setOnClickListener(this);  

        adb_password.addTextChangedListener(mEditText);  
    }  

    TextWatcher mEditText = new TextWatcher() {  
        private CharSequence temp;  

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

        @Override  
        public void beforeTextChanged(CharSequence s, int start, int count,  
                int after) {  
            adb_password.setVisibility(View.VISIBLE);  
            adb_lin2.setVisibility(View.GONE);  
        }  

        @Override  
        public void afterTextChanged(Editable s) {  
            if(adb_password.getText().length() == 6){  
                if(adb_password.getText().toString().equals("111111")){  
                    adb_password.setVisibility(View.GONE);  
                    adb_password.setFocusableInTouchMode(false);  
                    adb_password.setFocusable(false);  
                    adb_lin2.setVisibility(View.VISIBLE);  
                    adb_lin2.setFocusableInTouchMode(true);  
                    button1.requestFocus();  
                }  
            }  

        }  
    };  


    @Override  
    public void onClick(View v) {  
        switch (v.getId()) {  
        case R.id.button1:  
            Toast.makeText(KvAdb.this, "llll", 0).show();  
            break;  
        case R.id.button2:  

            finish();  
            break;  
        }  
    }  
}  </pre>
 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!