gpt4 book ai didi

android - 根据两个或多个 EditText 字段中的输入启用/禁用按钮的优雅方式

转载 作者:行者123 更新时间:2023-11-29 15:36:09 26 4
gpt4 key购买 nike

我看过这个问题 How to disable Button if EditText is empty ?

但那里只有 1 个 EditText 字段。如果两个 EditText 字段都为空或包含文本,使用 TextWatcher 启用或禁用 Button 的优雅解决方案是什么?

这是我的方法并且有效,但它没有使用 onTextChanged 中传递的任何参数。你怎么看?

public class MainActivity extends AppCompatActivity implements TextWatcher {
private EditText editTextUsername;
private EditText editTextPassword;
private Button buttonConfirm;

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

editTextUsername = findViewById(R.id.edit_text);
editTextPassword = findViewById(R.id.edit_password);
buttonConfirm = findViewById(R.id.button_confirm);


editTextUsername.addTextChangedListener(this);
editTextPassword.addTextChangedListener(this);
}

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

}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String usernameInput = editTextUsername.getText().toString().trim();
String passwordInput = editTextPassword.getText().toString().trim();

buttonConfirm.setEnabled(!usernameInput.isEmpty() && !passwordInput.isEmpty());
}

@Override
public void afterTextChanged(Editable s) {

}
}

最佳答案

您可以将 listeners 设置为 EditText

editTextUsername.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) {
button.setEnabled(editTextUsername.getText().toString().trim().length() > 0
&& editTextPassword .getText().toString().trim().length() > 0 );
}

@Override
public void afterTextChanged(Editable s) {

}
});

editTextPassword.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) {
button.setEnabled(editTextUsername.getText().toString().trim().length() > 0
&& editTextPassword .getText().toString().trim().length() > 0 );
}

@Override
public void afterTextChanged(Editable s) {

}
});

关于android - 根据两个或多个 EditText 字段中的输入启用/禁用按钮的优雅方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49688833/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com