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.annotation.SuppressLint;
21 import android.graphics.drawable.Drawable;
22 import android.text.Editable;
23 import android.text.TextWatcher;
24 import android.view.MotionEvent;
25 import android.view.View;
26 import android.widget.EditText;
28 import net.ktnx.mobileledger.R;
30 public class TextViewClearHelper {
31 private boolean hadText = false;
32 private boolean hasFocus = false;
33 private EditText view;
34 private TextWatcher textWatcher;
35 private View.OnFocusChangeListener prevOnFocusChangeListener;
36 public void detachFromView() {
39 view.removeTextChangedListener(textWatcher);
40 prevOnFocusChangeListener = null;
46 @SuppressLint("ClickableViewAccessibility")
47 public void attachToTextView(EditText view) {
48 if (this.view != null)
51 textWatcher = new TextWatcher() {
53 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
57 public void onTextChanged(CharSequence s, int start, int before, int count) {
61 public void afterTextChanged(Editable s) {
62 boolean hasText = s.length() > 0;
65 if (hadText && !hasText)
67 if (!hadText && hasText)
75 view.addTextChangedListener(textWatcher);
76 prevOnFocusChangeListener = view.getOnFocusChangeListener();
77 view.setOnFocusChangeListener((v, hasFocus) -> {
89 this.hasFocus = hasFocus;
91 if (prevOnFocusChangeListener != null)
92 prevOnFocusChangeListener.onFocusChange(v, hasFocus);
95 view.setOnTouchListener((v, event) -> this.onTouchEvent(view, event));
97 private void hideClearDrawable() {
98 view.setCompoundDrawablesRelative(null, null, null, null);
100 private void showClearDrawable() {
101 view.setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, R.drawable.ic_clear_black_24dp,
104 public boolean onTouchEvent(EditText view, MotionEvent event) {
105 if ((event.getAction() == MotionEvent.ACTION_UP) && (view.getText()
108 boolean clearClicked = false;
109 final float x = event.getX();
110 final int vw = view.getWidth();
111 // start, top, end, bottom (end == 2)
112 Drawable dwb = view.getCompoundDrawablesRelative()[2];
114 final int dw = dwb.getBounds()
116 if (view.getLayoutDirection() == View.LAYOUT_DIRECTION_LTR) {