Search code examples
androidbuttonradio-grouponcheckedchanged

Button only enable when texts are filled and button checked


I'm basically setting up a info collection activity. It has a radio group for the gender choice and edit texts for name and age.

I have implemented both the onCheckedChangeListener for the radio group and the textChangedListener for the edit texts so that the next button is only enabled when both the texts are filled and the radio button is checked. However, it only works that way when the radio button is checked then the texts are filled, but not the other way.

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

    nameTxt = findViewById(R.id.name);
    ageTxt = findViewById(R.id.age);
    nextBtn = findViewById(R.id.next);
    nextBtn.setEnabled(false);
    gender = findViewById(R.id.gender);

    nameTxt.addTextChangedListener(watcher);
    ageTxt.addTextChangedListener(watcher);

    gender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
    {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            onChecked = true;
        }
    });
}

private final TextWatcher watcher = new TextWatcher() {

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after)
    { }
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count)
    {}
    @Override
    public void afterTextChanged(Editable s) {
        if (nameTxt.getText().toString().length() == 0 || ageTxt.getText().toString().length() == 0 || onChecked == false) {
            nextBtn.setEnabled(false);
        } else {
            nextBtn.setEnabled(true);
        }
    }
};

I expected both listeners to work independently (that doing in any order would give the same result). I might be wrong here since I'm relatively new to Android Studio.


Solution

  • gender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            onChecked = true;
            validateNext();
        }
    });
    
    
    private final TextWatcher watcher = new TextWatcher() {
    
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
    
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            validateNext();
        }
    
        @Override
        public void afterTextChanged(Editable s) {}
    };
    
    private void validateNext() {
        if (TextUtils.isEmpty(nameTxt.getText().toString().trim())
             || TextUtils.isEmpty(ageTxt.getText().toString().trim())
             || onChecked == false) {
            nextBtn.setEnabled(false);
        } else {
            nextBtn.setEnabled(true);
        }
    }