1. 布局xml(仅贴出输入框部分)
2. 代码实现(仅贴出实现清除按钮功能部分代码)
// 清空用户名按钮
private Button clearNameButton = null;
// 清空密码按钮
private Button clearPswButton = null;
// 用户名输入框
private EditText edtUserCode = null;
// 密码输入框
private EditText edtPassWord = null;
edtUserCode = (EditText) this.findViewById(R.id.edt_username);
edtPassWord = (EditText) this.findViewById(R.id.edt_password);
edtUserCode.setSelection(edtUserCode.getText().length());
edtPassWord.setSelection(edtPassWord.getText().length());
clearNameButton = (Button) findViewById(R.id.button_name_clear);
clearPswButton = (Button) findViewById(R.id.button_psw_clear);
/**
* 用户名输入框监听事件
*/
edtUserCode.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
if (edtUserCode.getText().toString() != null
&& !edtUserCode.getText().toString().equals("")) {
clearNameButton.setVisibility(View.VISIBLE);
} else {
clearNameButton.setVisibility(View.INVISIBLE);
}
}
});
/**
* 密码输入框监听事件
*/
edtPassWord.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
if (edtPassWord.getText().toString() != null
&& !edtPassWord.getText().toString().equals("")) {
clearPswButton.setVisibility(View.VISIBLE);
} else {
clearPswButton.setVisibility(View.INVISIBLE);
}
}
});
/**
* 清空用户名按钮的监听事件
*/
clearNameButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
edtUserCode.setText("");
}
});
/**
* 清空密码按钮的监听事件
*/
clearPswButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
edtPassWord.setText("");
}
});