仅在填充文本并选中按钮时启用按钮

时间:2019-02-16 19:29:33

标签: android button radio-group oncheckedchanged

我基本上是在设置信息收集活动。它有一个用于选择性别的广播组,并编辑姓名和年龄的文本。

我已经为单选组实现了onCheckedChangeListener,为编辑文本实现了textChangedListener,以便仅当两个文本都被填充并且选中了单选按钮时才启用下一个按钮。但是,仅当选中单选按钮然后填充文本时,该方法才起作用,而反之则不行。

@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);
        }
    }
};

我希望两个监听器都可以独立工作(以任何顺序进行操作都会得到相同的结果)。我在这里可能是错的,因为我是Android Studio的新手。

1 个答案:

答案 0 :(得分:0)

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);
    }
}