Skip to content

Instantly share code, notes, and snippets.

@AB1209
Created November 22, 2018 07:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AB1209/b82357a8d8cb58b67cd446a9380b9815 to your computer and use it in GitHub Desktop.
Save AB1209/b82357a8d8cb58b67cd446a9380b9815 to your computer and use it in GitHub Desktop.
Customized view ClearableEditText
public class ClearableEditText extends RelativeLayout {
private final static String TAG = "ClearableEditText";
private LayoutInflater inflater = null;
private EditText edit_text;
private Button btn_clear;
public ClearableEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initViews();
}
public ClearableEditText(Context context, AttributeSet attrs) {
super(context, attrs);
initViews();
}
public ClearableEditText(Context context) {
super(context);
initViews();
}
private void initViews() {
inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.clearable_edit_text, this, true);
edit_text = (EditText) findViewById(R.id.clearable_edit);
btn_clear = (Button) findViewById(R.id.clearable_button_clear);
btn_clear.setVisibility(RelativeLayout.INVISIBLE);
clearText();
showHideClearButton();
}
private void clearText() {
btn_clear.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
edit_text.setText("");
}
});
}
private void showHideClearButton() {
edit_text.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() > 0)
btn_clear.setVisibility(RelativeLayout.VISIBLE);
else
btn_clear.setVisibility(RelativeLayout.INVISIBLE);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
public Editable getText() {
Editable text = edit_text.getText();
return text;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment