2 * Copyright © 2019 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.util.AttributeSet;
24 import android.view.MotionEvent;
25 import android.view.View;
27 import androidx.appcompat.widget.AppCompatAutoCompleteTextView;
29 import net.ktnx.mobileledger.R;
31 public final class AutoCompleteTextViewWithClear extends AppCompatAutoCompleteTextView {
32 private boolean hadText = false;
34 public AutoCompleteTextViewWithClear(Context context) {
37 public AutoCompleteTextViewWithClear(Context context, AttributeSet attrs) {
38 super(context, attrs);
40 public AutoCompleteTextViewWithClear(Context context, AttributeSet attrs, int defStyleAttr) {
41 super(context, attrs, defStyleAttr);
44 protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
46 if (getText().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) hideClearDrawable();
68 if (!hadText && hasText) showClearDrawable();
73 super.onTextChanged(text, start, lengthBefore, lengthAfter);
76 public boolean onTouchEvent(MotionEvent event) {
77 if (event.getAction() == MotionEvent.ACTION_UP) if (getText().length() > 0) {
78 boolean clearClicked = false;
79 final float x = event.getX();
80 final int vw = getWidth();
81 // start, top, end, bottom (end == 2)
82 Drawable dwb = getCompoundDrawablesRelative()[2];
84 final int dw = dwb.getBounds().width();
85 if (getLayoutDirection() == View.LAYOUT_DIRECTION_LTR) {
86 if ((x > vw - dw)) clearClicked = true;
89 if (x < vw - dw) clearClicked = true;
100 return super.onTouchEvent(event);
103 public boolean performClick() {
104 return super.performClick();