textWatcher
对象后,如果chatText
(编辑文本)为空,我想禁用发送按钮并将其设置为灰色我认为这是排名问题。请帮忙。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
list = (ListView)findViewById(R.id.listView);
list.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
chatText = (EditText)findViewById(R.id.editText);
//chatText.setOnKeyListener(this);
me = true;
send = (Button)findViewById(R.id.button);
change = (Button)findViewById(R.id.button2);
list.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
adp = new TheAdapter(getApplicationContext(),R.layout.chat);
list.setAdapter(adp);
chatText.addTextChangedListener(textWatcher);
checkFieldsForEmptyValues();
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
envoyer();
}
});
change.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
me = !me;
if (!me) {
change.setText(R.string.sender2);
} else {
change.setText(R.string.sender);
}
}
});
}
public void envoyer(){
adp.add(new messages(me, chatText.getText().toString()));
chatText.setText("");
}
private void checkFieldsForEmptyValues(){
String s1 = chatText.getText().toString();
if (s1.length() < 0 ) {
send.setEnabled(false);
} else {
send.setEnabled(true);
send.setBackgroundColor(Color.BLUE);
//send.setBackgroundColor((getResources().getColor(R.color.blue)));
}
}
答案 0 :(得分:0)
在onTextChanged
中,您可以检查文本字段是否为空:
chatText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() > 0) { //enable}
else if (s.length() == 0 { //disable }
在您的代码中,您有if (s1.length() < 0 )
,我认为这不会是真的,因为文本大小永远不会小于0.
答案 1 :(得分:0)
// Disable on init
send.setEnabled(false);
// add text changer
chatText.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) {
// Enable when input is != null and not empty. You can check string lenght too
send.setEnabled(s != null && !s.toString().isEmpty());
}
@Override
public void afterTextChanged(Editable s) {
}
});
之前禁用按钮并添加textwatch。您还可以检查edittext值是否为空或验证字符串长度。
我希望它能帮到你