2012-01-05 52 views
0

我有一些EditText的和一些TextView的旁边,当一个字段没有填写时,TextView需要是红色的。我有以下代码来完成此操作。TextWatcher的行为不如预期

final TextView textSoftware = (TextView) findViewById(R.id.textViewSoftware); 
    final EditText fieldSoftware = (EditText) findViewById(R.id.fieldSoftware); 

    fieldSoftware.addTextChangedListener(new TextWatcher() { 
     public void afterTextChanged(Editable s) { 
      if (!fieldSoftware.getText().toString().trim().equals("")) { 
       textSoftware.setTextColor(Color.WHITE); 
      }else{ 
       textSoftware.setTextColor(Color.RED); 
      } 
     } 

     public void beforeTextChanged(CharSequence s, int start, int count, 
       int after) { 
     } 

     public void onTextChanged(CharSequence s, int start, int before, 
       int count) { 
     }; 
    }); 

但是,当我只是重复这个片段的其他领域和textviews,else语句似乎不起作用。它会变成白色,但在清除输入时不会变回红色。

回答

2
if (fieldSoftware.length()<=0) { 
       textSoftware.setTextColor(Color.WHITE); 
      }else{ 
       textSoftware.setTextColor(Color.RED); 
      } 
+0

是的,这个工作完美无瑕的各个领域。非常感谢! – MaikelS 2012-01-05 09:13:05

0

为了更好的响应使用此

if (fieldSoftware.getText().toString().trim().isEmpty()) { 
     textSoftware.setTextColor(Color.RED); 
}else{ 
     textSoftware.setTextColor(Color.WHITE); 
}