2 * Copyright © 2020 Damyan Ivanov.
3 * This file is part of MoLe.
4 * MoLe is free software: you can distribute it and/or modify it
5 * under the term of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your opinion), any later version.
9 * MoLe is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License terms for details.
14 * You should have received a copy of the GNU General Public License
15 * along with MoLe. If not, see <https://www.gnu.org/licenses/>.
18 package net.ktnx.mobileledger.ui;
20 import android.content.Context;
21 import android.graphics.Rect;
22 import android.graphics.drawable.Drawable;
23 import android.text.Editable;
24 import android.util.AttributeSet;
25 import android.view.MotionEvent;
26 import android.view.View;
28 import net.ktnx.mobileledger.R;
30 public final class EditTextWithClear extends androidx.appcompat.widget.AppCompatEditText {
31 private boolean hadText = false;
33 public EditTextWithClear(Context context) {
36 public EditTextWithClear(Context context, AttributeSet attrs) {
37 super(context, attrs);
39 public EditTextWithClear(Context context, AttributeSet attrs, int defStyleAttr) {
40 super(context, attrs, defStyleAttr);
43 protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
45 final Editable text = getText();
46 if ((text != null) && (text.length() > 0)) {
54 super.onFocusChanged(focused, direction, previouslyFocusedRect);
56 private void hideClearDrawable() {
57 setCompoundDrawablesRelative(null, null, null, null);
59 private void showClearDrawable() {
60 setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, R.drawable.ic_clear_accent_24dp, 0);
63 protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
64 final boolean hasText = text.length() > 0;
67 if (hadText && !hasText)
69 if (!hadText && hasText)
75 super.onTextChanged(text, start, lengthBefore, lengthAfter);
78 public boolean onTouchEvent(MotionEvent event) {
79 if (event.getAction() == MotionEvent.ACTION_UP) {
80 final Editable text = getText();
81 if ((text != null) && (text.length() > 0)) {
82 boolean clearClicked = false;
83 final float x = event.getX();
84 final int vw = getWidth();
85 // start, top, end, bottom (end == 2)
86 Drawable dwb = getCompoundDrawablesRelative()[2];
88 final int dw = dwb.getBounds()
90 if (getLayoutDirection() == View.LAYOUT_DIRECTION_LTR) {
108 return super.onTouchEvent(event);
111 public boolean performClick() {
112 return super.performClick();