使用saripaar对android输入控件进行快速验证

saripaar是个android的第三方快速校验,使用注解快速添加验证规则。
public class LoginActivity extends Activity  implements 

ValidationListener

   {

@Required(order = 1, message="用户名不能为空")

    private EditText tbxUser=null;
    

@Required(order = 2,message="密码不能为空")

    private EditText tbxPsw =null;
    
    private Validator validator;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
        //初始化监听
        initListener();
        //实例化校验类库
       

validator = new Validator(this); validator.setValidationListener(this);

    }

    /**
     * 初始化监听
     */
    private void initListener() {
        
        Button btn = (Button)this.findViewById(R.id.btnLogin);
        tbxUser=(EditText)this.findViewById(R.id.txtUser);
        tbxPsw=(EditText)this.findViewById(R.id.txtPassword);
        
        btn.setOnClickListener(new OnClickListener(){
            public void onClick(View v){
                validator.validate();
            }


        });
    }
    private void login() {
                 Dialog.showAlert(“Logining”, this );
             };
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public void preValidation() {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void onSuccess() {
        // TODO Auto-generated method stub
      

login();

    }

    @Override
    public void onFailure(View failedView, Rule<?> failedRule) {
        // TODO Auto-generated method stub
      

String message = failedRule.getFailureMessage(); if (failedView instanceof EditText) { failedView.requestFocus(); ((EditText) failedView).setError(message); } else { Dialog.showToast(message,this); }

    }

    @Override
    public void onValidationCancelled() {
        // TODO Auto-generated method stub
        
    }

}

你可能感兴趣的:(android)