使用TextWatcher进行Android验证



尽管有问题名称,但这实际上更多地与基本OOP有关。

对我来说,使用TextWatcher进行表单输入验证(经过一些研究)似乎是Android上最有效的验证方式。然而,我遇到了一个相当初级的问题。

public class MatchConfig extends Activity implements TextWatcher {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_match_config);
        // Show the Up button in the action bar.
        setupActionBar();
        final EditText teamA = (EditText) findViewById(R.id.teamA_editText); //Team A input
        teamA.addTextChangedListener(this);   //Team A validation
        final EditText teamB = (EditText) findViewById(R.id.teamB_editText);  //Team B input
        teamB.addTextChangedListener(this);   //Team B validation
        final EditText halves = (EditText) findViewById(R.id.halves_editText);  //halves input
        halves.addTextChangedListener(this);   //halves validation
            Button start = (Button) findViewById(R.id.start_button);
start.setOnClickListener(new OnClickListener() {
    // SEND OFF TO DATABASE HANDLING
)}
//Other Stuff
@Override
    public void afterTextChanged(Editable arg0) {
        // TODO Auto-generated method stub
         //Guard against SQL injection, etc.
        Toast.makeText(this, "after text test", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
        // TODO Auto-generated method stub
        Toast.makeText(this, "before text test", Toast.LENGTH_SHORT).show();
    }
    @Override
    public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
        // TODO Auto-generated method stub
        Toast.makeText(this, "on text test", Toast.LENGTH_SHORT).show();
    }

虽然这段代码有效,但我看不出如何为单独的表单元素实现不同的afterTextChanged方法。对于不同类型的输入,验证自然会有所不同。虽然我可以重载(而不是重写)像afterTextChanged这样的方法,但我没有办法通过这些方法直接调用它(因此无法指定参数来专门使用重载的方法)。

一个小问题是:有没有办法减少这种实现可能需要在安卓设备上进行的处理?我担心这种对用户输入的每个字符的调用会占用CPU。

您应该为每个EditText创建一个TextWatcher,而不是像处理OnClickListener那样让"活动"实现TextWatcher。

顺便说一句,您通常应该将TextWatchers设置在onResume()中(或者至少在onRestoreInstanceState()之后)。否则,当EditText恢复以前输入的文本时(在用户更改设备配置的情况下,例如旋转手机),TextWatcher可能会触发。

您可以在例如的TextChanged之后在里面有一个开关案例

@Override
    public void afterTextChanged(Editable arg0) {
       switch(arg0.getId()){
           case R.id.teamA_editText:
           break;
           case R.id.teamB_editText:
           break;
           case R.id.teamC_editText:
           break;
       }
        Toast.makeText(this, "after text test", Toast.LENGTH_SHORT).show();
    }

最新更新