我想将我的按钮设置为活动状态,仅当两个EditTexts不为空时。我尝试使用TextWatcher,但它并没有真正正常工作 - 按钮保持活动状态,即使从价格输入中删除所有文本也是如此。这是我的代码:
final EditText titleEdit = findViewById(R.id.name);
final EditText priceEdit = findViewById(R.id.price);
final Button addButton = findViewById(R.id.add);
titleEdit.addTextChangedListener(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) {
if (!TextUtils.isEmpty(titleEdit.getText().toString().trim()) && !TextUtils.isEmpty(priceEdit.getText().toString().trim()))
addButton.setEnabled(true);
else addButton.setEnabled(false);
}
@Override
public void afterTextChanged(Editable s) {
}
});
我尝试了Stackoverflow的一些解决方案,但它仍然是一样的。我应该在代码中更改什么?
答案 0 :(得分:1)
TextWatcher
。if (s.length()>0))
尝试
titleEdit.addTextChangedListener(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) {
if (s.length()>0))
{
addButton.setEnabled(true);
}
else
{
addButton.setEnabled(false);
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
priceEdit.addTextChangedListener(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) {
if (s.length()>0))
{
addButton.setEnabled(true);
}
else
{
addButton.setEnabled(false);
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
答案 1 :(得分:1)
将以下变量定义为全局变量
Boolean text1= false;
Boolean text2 = false;
完整代码
public class classname extends AppCompatActivity {
Boolean text1= false;
Boolean text2 = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
//Your code
titleEdit.addTextChangedListener(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) {
if (s.length() > 0 ){
text1 = true;
if(text1 && text2){
addButton.setEnabled(true);
}
}else{
text1 = false;
addButton.setEnabled(false);
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
priceEdit.addTextChangedListener(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) {
if (s.length() >0 ){
text2 = true;
if(text1 && text2){
addButton.setEnabled(true);
}
}else{
text2 = false;
addButton.setEnabled(false);
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
}