public class ActivityMain extends AppCompatActivity {
Button button;
TextView tv;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=findViewById(R.id.button_chatbox_send);
button.setEnabled(false);
tv= findViewById(R.id.edittext_chatbox);
tv.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int start, int before, int count) {
if (charSequence.toString().equals("")) {
button.setEnabled(false);
} else {
button.setEnabled(true);
}
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
}
});
button.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
//Call other method with string from text view as parameter
}
}
});
}
我在TextView中添加了TextChangedListener以禁用Button,而文本视图不包含字符串。在运行时,在我将字符串输入TextView后,即使我删除了所有文本,按钮仍然处于启用状态。如何解决这个问题,我在点击时使用的方法不能用空字符串?
修改
问题解决了。
答案 0 :(得分:1)
在onTextChanged或textChanged
之后更新您的按钮tv.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
button.setEnabled(!TextUtils.isEmpty(s.toString())); // Update button here OR
}
@Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
button.setEnabled(count>0); // Update button here
}
});
答案 1 :(得分:0)
将其移至afterTextChanged
@Override
public void afterTextChanged(Editable editable) {
button.setEnabled(!TextUtils.isEmpty(editable.toString()));
}
答案 2 :(得分:0)
您应该在onTextChanged
-
TextWatcher
方法中停用该按钮
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
button.setEnabled(charSequence.toString().length() > 0);
}