Android中的按钮不会禁用

时间:2013-02-21 19:08:03

标签: java android button

public void enableButton(){
      exitButton.setEnabled(true);
}
public void disableButton(){
      exitButton.setEnabled(false);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second_page);
    InputFilter[] FilterArray = new InputFilter[1];
    FilterArray[0] = new InputFilter.LengthFilter(4);
    initializeEverything();
    text1.setFilters(FilterArray);
    text2.setFilters(FilterArray);
    text3.setFilters(FilterArray);
    text4.setFilters(FilterArray);
    text5.setFilters(FilterArray);

    final TextView textfinal = (TextView)findViewById(R.id.finaltext);


    TextWatcher textWatcher = new TextWatcher() {

      public void afterTextChanged(Editable s) {
          textfinal.setText(calculateTotal());
          if(Double.parseDouble(textfinal.getText().toString())>100)
              textfinal.setTextColor(Color.RED);
              disableButton();
              Log.i("yo","gray this out");
          if(Double.parseDouble(textfinal.getText().toString())<100)
              textfinal.setTextColor(Color.BLACK);
              enableButton();
      }

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

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

      }
    };
    text1.addTextChangedListener(textWatcher);
    text2.addTextChangedListener(textWatcher);
    text3.addTextChangedListener(textWatcher);
    text4.addTextChangedListener(textWatcher);
    text5.addTextChangedListener(textWatcher);

我在退出exitButton时遇到了问题。在initializeEverything()中,我设置了exitButton.setEnabled(false),它在开头是灰色的。在我输入一些低于100的数字值到editTexts(text1,text2 ...)后,按钮变为启用状态。但是当我超过100时,应该再次禁用它,但它会保持启用状态。发送了Logcat消息“grey this shit out”,所以我知道textWatcher工作正常,我不知道为什么按钮不会禁用。

1 个答案:

答案 0 :(得分:4)

问题在于这些行

if(Double.parseDouble(textfinal.getText().toString())>100)
          textfinal.setTextColor(Color.RED);
          disableButton();
          Log.i("yo","gray this out");
 if(Double.parseDouble(textfinal.getText().toString())<100)
          textfinal.setTextColor(Color.BLACK);
          enableButton();

请注意,如果您不使用括号,if只会附加一行。将这些行替换为:

if(Double.parseDouble(textfinal.getText().toString())>100){
          textfinal.setTextColor(Color.RED);
          disableButton();
          Log.i("yo","gray this out");
}else if(Double.parseDouble(textfinal.getText().toString())<100){
          textfinal.setTextColor(Color.BLACK);
          enableButton();
}