-
Notifications
You must be signed in to change notification settings - Fork 383
Expand file tree
/
Copy pathTokenCompleteTextView.java
More file actions
1636 lines (1420 loc) · 58.6 KB
/
TokenCompleteTextView.java
File metadata and controls
1636 lines (1420 loc) · 58.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package com.tokenautocomplete;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.*;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.accessibility.AccessibilityEvent;
import android.view.inputmethod.*;
import android.widget.Filter;
import android.widget.ListView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.UiThread;
import androidx.appcompat.widget.AppCompatAutoCompleteTextView;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* GMail style auto complete view with easy token customization
* override getViewForObject to provide your token view
* <br>
* Created by mgod on 9/12/13.
*
* @author mgod
*/
public abstract class TokenCompleteTextView<T> extends AppCompatAutoCompleteTextView
implements TextView.OnEditorActionListener, ViewSpan.Layout {
//Logging
public static final String TAG = "TokenAutoComplete";
//When the user clicks on a token...
public enum TokenClickStyle {
None(false), //...do nothing, but make sure the cursor is not in the token
Delete(false),//...delete the token
Select(true),//...select the token. A second click will delete it.
SelectDeselect(true);
private boolean mIsSelectable;
TokenClickStyle(final boolean selectable) {
mIsSelectable = selectable;
}
public boolean isSelectable() {
return mIsSelectable;
}
}
private Tokenizer tokenizer;
private T selectedObject;
private TokenListener<T> listener;
private TokenSpanWatcher spanWatcher;
private TokenTextWatcher textWatcher;
private CountSpan countSpan;
private @Nullable
SpannableStringBuilder hiddenContent;
private TokenClickStyle tokenClickStyle = TokenClickStyle.None;
private CharSequence prefix = "";
private boolean prefixEnabled = true;
private boolean hintVisible = false;
private Layout lastLayout = null;
private boolean initialized = false;
private boolean performBestGuess = true;
private boolean preventFreeFormText = true;
private boolean savingState = false;
private boolean shouldFocusNext = false;
private boolean allowCollapse = true;
private boolean internalEditInProgress = false;
private int tokenLimit = -1;
private transient String lastCompletionText = null;
/**
* Add the TextChangedListeners
*/
protected void addListeners() {
Editable text = getText();
if (text != null) {
text.setSpan(spanWatcher, 0, text.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
addTextChangedListener(textWatcher);
}
}
/**
* Remove the TextChangedListeners
*/
protected void removeListeners() {
Editable text = getText();
if (text != null) {
TokenSpanWatcher[] spanWatchers = text.getSpans(0, text.length(), TokenSpanWatcher.class);
for (TokenSpanWatcher watcher : spanWatchers) {
text.removeSpan(watcher);
}
removeTextChangedListener(textWatcher);
}
}
/**
* Initialise the variables and various listeners
*/
private void init() {
if (initialized) return;
// Initialise variables
setTokenizer(new CharacterTokenizer(Arrays.asList(',', ';'), ","));
Editable text = getText();
assert null != text;
spanWatcher = new TokenSpanWatcher();
textWatcher = new TokenTextWatcher();
hiddenContent = null;
countSpan = new CountSpan();
// Initialise TextChangedListeners
addListeners();
setTextIsSelectable(false);
setLongClickable(false);
//In theory, get the soft keyboard to not supply suggestions. very unreliable
setInputType(getInputType() |
InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS |
InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE);
setHorizontallyScrolling(false);
// Listen to IME action keys
setOnEditorActionListener(this);
// Initialise the text filter (listens for the split chars)
setFilters(new InputFilter[]{new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int destinationStart, int destinationEnd) {
if (internalEditInProgress) {
return null;
}
// Token limit check
if (tokenLimit != -1 && getObjects().size() == tokenLimit) {
return "";
}
//Detect split characters, remove them and complete the current token instead
if (tokenizer.containsTokenTerminator(source)) {
//Only perform completion if we don't allow free form text, or if there's enough
//content to believe this should be a token
if (preventFreeFormText || currentCompletionText().length() > 0) {
performCompletion();
return "";
}
}
//We need to not do anything when we would delete the prefix
if (destinationStart < prefix.length()) {
//when setText is called, which should only be called during restoring,
//destinationStart and destinationEnd are 0. If not checked, it will clear out
//the prefix.
//This is why we need to return null in this if condition to preserve state.
if (destinationStart == 0 && destinationEnd == 0) {
return null;
} else if (destinationEnd <= prefix.length()) {
//Don't do anything
return prefix.subSequence(destinationStart, destinationEnd);
} else {
//Delete everything up to the prefix
return prefix.subSequence(destinationStart, prefix.length());
}
}
return null;
}
}});
initialized = true;
}
public TokenCompleteTextView(Context context) {
super(context);
init();
}
public TokenCompleteTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public TokenCompleteTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
@Override
protected void performFiltering(CharSequence text, int keyCode) {
Filter filter = getFilter();
if (filter != null) {
filter.filter(currentCompletionText(), this);
}
}
public void setTokenizer(Tokenizer t) {
tokenizer = t;
}
/**
* Set the action to be taken when a Token is clicked
*
* @param cStyle The TokenClickStyle
*/
public void setTokenClickStyle(TokenClickStyle cStyle) {
tokenClickStyle = cStyle;
}
/**
* Set the listener that will be notified of changes in the Token list
*
* @param l The TokenListener
*/
public void setTokenListener(TokenListener<T> l) {
listener = l;
}
/**
* Override if you want to prevent a token from being added. Defaults to false.
*
* @param token the token to check
* @return true if the token should not be added, false if it's ok to add it.
*/
public boolean shouldIgnoreToken(@SuppressWarnings("unused") T token) {
return false;
}
/**
* Override if you want to prevent a token from being removed. Defaults to true.
*
* @param token the token to check
* @return false if the token should not be removed, true if it's ok to remove it.
*/
public boolean isTokenRemovable(@SuppressWarnings("unused") T token) {
return true;
}
/**
* There is an issue if onRestoreState of the objects is not desired, the setting of the prefix
* overrides any existing in `text`. This option allows callers to disable that feature.
*
* @param enabled whether to enable the prefix
*/
public void setPrefixEnabled(boolean enabled) {
this.prefixEnabled = enabled;
}
/**
* A String of text that is shown before all the tokens inside the EditText
* (Think "To: " in an email address field. I would advise against this: use a label and a hint.
*
* @param p String with the hint
*/
public void setPrefix(CharSequence p) {
//Have to clear and set the actual text before saving the prefix to avoid the prefix filter
CharSequence prevPrefix = prefix;
prefix = p;
Editable text = getText();
if (text != null) {
internalEditInProgress = true;
if (prevPrefix != null) {
text.replace(0, prevPrefix.length(), p);
} else {
text.insert(0, p);
}
internalEditInProgress = false;
}
//prefix = p;
updateHint();
}
/**
* <p>You can get a color integer either using
* {@link androidx.core.content.ContextCompat#getColor(android.content.Context, int)}
* or with {@link android.graphics.Color#parseColor(String)}.</p>
* <p>{@link android.graphics.Color#parseColor(String)}
* accepts these formats (copied from android.graphics.Color):
* You can use: '#RRGGBB', '#AARRGGBB'
* or one of the following names: 'red', 'blue', 'green', 'black', 'white',
* 'gray', 'cyan', 'magenta', 'yellow', 'lightgray', 'darkgray', 'grey',
* 'lightgrey', 'darkgrey', 'aqua', 'fuchsia', 'lime', 'maroon', 'navy',
* 'olive', 'purple', 'silver', 'teal'.</p>
*
* @param prefix prefix
* @param color A single color value in the form 0xAARRGGBB.
*/
@SuppressWarnings("SameParameterValue")
public void setPrefix(CharSequence prefix, int color) {
SpannableString spannablePrefix = new SpannableString(prefix);
spannablePrefix.setSpan(new ForegroundColorSpan(color), 0, spannablePrefix.length(), 0);
setPrefix(spannablePrefix);
}
/**
* Get the list of Tokens
*
* @return List of tokens
*/
public List<T> getObjects() {
ArrayList<T> objects = new ArrayList<>();
Editable text = getText();
if (hiddenContent != null) {
text = hiddenContent;
}
for (TokenImageSpan span : text.getSpans(0, text.length(), TokenImageSpan.class)) {
objects.add(span.getToken());
}
return objects;
}
/**
* Get the content entered in the text field, including hidden text when ellipsized
*
* @return CharSequence of the entered content
*/
public CharSequence getContentText() {
if (hiddenContent != null) {
return hiddenContent;
} else {
return getText();
}
}
/**
* Set whether we try to guess an entry from the autocomplete spinner or just use the
* defaultObject implementation for inline token completion.
*
* @param guess true to enable guessing
*/
public void performBestGuess(boolean guess) {
performBestGuess = guess;
}
/**
* If set to true, the only content in this view will be the tokens and the current completion
* text. Use this setting to create things like lists of email addresses. If false, it the view
* will allow text in addition to tokens. Use this if you want to use the token search to find
* things like user names or hash tags to put in with text.
*
* @param prevent true to prevent non-token text. Defaults to true.
*/
public void preventFreeFormText(boolean prevent) {
preventFreeFormText = prevent;
}
/**
* Set whether the view should collapse to a single line when it loses focus.
*
* @param allowCollapse true if it should collapse
*/
public void allowCollapse(boolean allowCollapse) {
this.allowCollapse = allowCollapse;
}
/**
* Set a number of tokens limit.
*
* @param tokenLimit The number of tokens permitted. -1 value disables limit.
*/
@SuppressWarnings("unused")
public void setTokenLimit(int tokenLimit) {
this.tokenLimit = tokenLimit;
}
/**
* A token view for the object
*
* @param object the object selected by the user from the list
* @return a view to display a token in the text field for the object
*/
abstract protected View getViewForObject(T object);
/**
* Provides a default completion when the user hits , and there is no item in the completion
* list
*
* @param completionText the current text we are completing against
* @return a best guess for what the user meant to complete or null if you don't want a guess
*/
abstract protected T defaultObject(String completionText);
/**
* Correctly build accessibility string for token contents
* <p>
* This seems to be a hidden API, but there doesn't seem to be another reasonable way
*
* @return custom string for accessibility
*/
@SuppressWarnings("unused")
public CharSequence getTextForAccessibility() {
if (getObjects().size() == 0) {
return getText();
}
SpannableStringBuilder description = new SpannableStringBuilder();
Editable text = getText();
int selectionStart = -1;
int selectionEnd = -1;
int i;
//Need to take the existing tet buffer and
// - replace all tokens with a decent string representation of the object
// - set the selection span to the corresponding location in the new CharSequence
for (i = 0; i < text.length(); ++i) {
//See if this is where we should start the selection
int origSelectionStart = Selection.getSelectionStart(text);
if (i == origSelectionStart) {
selectionStart = description.length();
}
int origSelectionEnd = Selection.getSelectionEnd(text);
if (i == origSelectionEnd) {
selectionEnd = description.length();
}
//Replace token spans
TokenImageSpan[] tokens = text.getSpans(i, i, TokenImageSpan.class);
if (tokens.length > 0) {
TokenImageSpan token = tokens[0];
description = description.append(tokenizer.wrapTokenValue(token.getToken().toString()));
i = text.getSpanEnd(token);
continue;
}
description = description.append(text.subSequence(i, i + 1));
}
int origSelectionStart = Selection.getSelectionStart(text);
if (i == origSelectionStart) {
selectionStart = description.length();
}
int origSelectionEnd = Selection.getSelectionEnd(text);
if (i == origSelectionEnd) {
selectionEnd = description.length();
}
if (selectionStart >= 0 && selectionEnd >= 0) {
Selection.setSelection(description, selectionStart, selectionEnd);
}
return description;
}
/**
* Clear the completion text only.
*/
@SuppressWarnings("unused")
public void clearCompletionText() {
//Respect currentCompletionText in case hint is visible or if other checks are added.
if (currentCompletionText().length() == 0) {
return;
}
Range currentRange = getCurrentCandidateTokenRange();
internalEditInProgress = true;
getText().delete(currentRange.start, currentRange.end);
internalEditInProgress = false;
}
@Override
public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
super.onInitializeAccessibilityEvent(event);
if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED) {
CharSequence text = getTextForAccessibility();
event.setFromIndex(Selection.getSelectionStart(text));
event.setToIndex(Selection.getSelectionEnd(text));
event.setItemCount(text.length());
}
}
private Range getCurrentCandidateTokenRange() {
Editable editable = getText();
int cursorEndPosition = getSelectionEnd();
int candidateStringStart = prefix.length();
int candidateStringEnd = editable.length();
if (hintVisible) {
//Don't try to search the hint for possible tokenizable strings
candidateStringEnd = candidateStringStart;
}
//We want to find the largest string that contains the selection end that is not already tokenized
TokenImageSpan[] spans = editable.getSpans(prefix.length(), editable.length(), TokenImageSpan.class);
for (TokenImageSpan span : spans) {
int spanEnd = editable.getSpanEnd(span);
if (candidateStringStart < spanEnd && cursorEndPosition >= spanEnd) {
candidateStringStart = spanEnd;
}
int spanStart = editable.getSpanStart(span);
if (candidateStringEnd > spanStart && cursorEndPosition <= spanEnd) {
candidateStringEnd = spanStart;
}
}
List<Range> tokenRanges = tokenizer.findTokenRanges(editable, candidateStringStart, candidateStringEnd);
for (Range range : tokenRanges) {
if (range.start <= cursorEndPosition && cursorEndPosition <= range.end) {
return range;
}
}
return new Range(cursorEndPosition, cursorEndPosition);
}
/**
* Override if you need custom logic to provide a sting representation of a token
*
* @param token the token to convert
* @return the string representation of the token. Defaults to {@link Object#toString()}
*/
protected CharSequence tokenToString(T token) {
return token.toString();
}
protected String currentCompletionText() {
if (hintVisible) return ""; //Can't have any text if the hint is visible
Editable editable = getText();
Range currentRange = getCurrentCandidateTokenRange();
String result = TextUtils.substring(editable, currentRange.start, currentRange.end);
Log.d(TAG, "Current completion text: " + result);
return result;
}
protected float maxTextWidth() {
return getWidth() - getPaddingLeft() - getPaddingRight();
}
@Override
public int getMaxViewSpanWidth() {
return (int) maxTextWidth();
}
public void redrawTokens() {
// There's no straight-forward way to convince the widget to redraw the text and spans. We trigger a redraw by
// making an invisible change (either adding or removing a dummy span).
Editable text = getText();
if (text == null) return;
int textLength = text.length();
DummySpan[] dummySpans = text.getSpans(0, textLength, DummySpan.class);
if (dummySpans.length > 0) {
text.removeSpan(DummySpan.INSTANCE);
} else {
text.setSpan(DummySpan.INSTANCE, 0, textLength, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
}
}
@Override
public boolean enoughToFilter() {
if (tokenizer == null || hintVisible) {
return false;
}
int cursorPosition = getSelectionEnd();
if (cursorPosition < 0) {
return false;
}
Range currentCandidateRange = getCurrentCandidateTokenRange();
//Don't allow 0 length entries to filter
return currentCandidateRange.length() >= Math.max(getThreshold(), 1);
}
@Override
public void performCompletion() {
if ((getAdapter() == null || getListSelection() == ListView.INVALID_POSITION) && enoughToFilter()) {
Object bestGuess;
if (getAdapter() != null && getAdapter().getCount() > 0 && performBestGuess) {
bestGuess = getAdapter().getItem(0);
} else {
bestGuess = defaultObject(currentCompletionText());
}
replaceText(convertSelectionToString(bestGuess));
} else {
super.performCompletion();
}
}
@Override
public InputConnection onCreateInputConnection(@NonNull EditorInfo outAttrs) {
InputConnection superConn = super.onCreateInputConnection(outAttrs);
if (superConn != null) {
TokenInputConnection conn = new TokenInputConnection(superConn, true);
outAttrs.imeOptions &= ~EditorInfo.IME_FLAG_NO_ENTER_ACTION;
outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_EXTRACT_UI;
return conn;
} else {
return null;
}
}
/**
* Create a token and hide the keyboard when the user sends the DONE IME action
* Use IME_NEXT if you want to create a token and go to the next field
*/
private void handleDone() {
// Attempt to complete the current token token
performCompletion();
// Hide the keyboard
InputMethodManager imm = (InputMethodManager) getContext().getSystemService(
Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(getWindowToken(), 0);
}
}
@Override
public boolean onKeyUp(int keyCode, @NonNull KeyEvent event) {
boolean handled = super.onKeyUp(keyCode, event);
if (shouldFocusNext) {
shouldFocusNext = false;
handleDone();
}
return handled;
}
@Override
public boolean onKeyDown(int keyCode, @NonNull KeyEvent event) {
boolean handled = false;
switch (keyCode) {
case KeyEvent.KEYCODE_TAB:
case KeyEvent.KEYCODE_ENTER:
case KeyEvent.KEYCODE_DPAD_CENTER:
if (event.hasNoModifiers()) {
shouldFocusNext = true;
handled = true;
}
break;
case KeyEvent.KEYCODE_DEL:
handled = !canDeleteSelection(1) || deleteSelectedObject();
break;
}
return handled || super.onKeyDown(keyCode, event);
}
private boolean deleteSelectedObject() {
if (tokenClickStyle != null && tokenClickStyle.isSelectable()) {
Editable text = getText();
if (text == null) return false;
TokenImageSpan[] spans = text.getSpans(0, text.length(), TokenImageSpan.class);
for (TokenImageSpan span : spans) {
if (span.view.isSelected()) {
removeSpan(text, span);
return true;
}
}
}
return false;
}
@Override
public boolean onEditorAction(TextView view, int action, KeyEvent keyEvent) {
if (action == EditorInfo.IME_ACTION_DONE) {
handleDone();
return true;
}
return false;
}
@Override
public boolean onTouchEvent(@NonNull MotionEvent event) {
int action = event.getActionMasked();
Editable text = getText();
boolean handled = false;
if (tokenClickStyle == TokenClickStyle.None) {
handled = super.onTouchEvent(event);
}
if (isFocused() && text != null && lastLayout != null && action == MotionEvent.ACTION_UP) {
int offset = getOffsetForPosition(event.getX(), event.getY());
if (offset != -1) {
TokenImageSpan[] links = text.getSpans(offset, offset, TokenImageSpan.class);
if (links.length > 0) {
links[0].onClick();
handled = true;
} else {
//We didn't click on a token, so if any are selected, we should clear that
clearSelections();
}
}
}
if (!handled && tokenClickStyle != TokenClickStyle.None) {
handled = super.onTouchEvent(event);
}
return handled;
}
@Override
protected void onSelectionChanged(int selStart, int selEnd) {
if (hintVisible) {
//Don't let users select the hint
selStart = 0;
}
//Never let users select text
selEnd = selStart;
if (tokenClickStyle != null && tokenClickStyle.isSelectable()) {
Editable text = getText();
if (text != null) {
clearSelections();
}
}
if (prefix != null && (selStart < prefix.length() || selEnd < prefix.length())) {
//Don't let users select the prefix
setSelection(prefix.length());
} else {
Editable text = getText();
if (text != null) {
//Make sure if we are in a span, we select the spot 1 space after the span end
TokenImageSpan[] spans = text.getSpans(selStart, selEnd, TokenImageSpan.class);
for (TokenImageSpan span : spans) {
int spanEnd = text.getSpanEnd(span);
if (selStart <= spanEnd && text.getSpanStart(span) < selStart) {
if (spanEnd == text.length())
setSelection(spanEnd);
else
setSelection(spanEnd + 1);
return;
}
}
}
super.onSelectionChanged(selStart, selEnd);
}
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
lastLayout = getLayout(); //Used for checking text positions
}
/**
* Collapse the view by removing all the tokens not on the first line. Displays a "+x" token.
* Restores the hidden tokens when the view gains focus.
*
* @param hasFocus boolean indicating whether we have the focus or not.
*/
public void performCollapse(boolean hasFocus) {
internalEditInProgress = true;
if (!hasFocus) {
// Display +x thingy/ellipse if appropriate
final Editable text = getText();
if (text != null && hiddenContent == null && lastLayout != null) {
//Ellipsize copies spans, so we need to stop listening to span changes here
text.removeSpan(spanWatcher);
CountSpan temp = preventFreeFormText ? countSpan : null;
Spanned ellipsized = SpanUtils.ellipsizeWithSpans(prefix, temp, getObjects().size(),
lastLayout.getPaint(), text, maxTextWidth());
if (ellipsized != null) {
hiddenContent = new SpannableStringBuilder(text);
setText(ellipsized);
TextUtils.copySpansFrom(ellipsized, 0, ellipsized.length(),
TokenImageSpan.class, getText(), 0);
TextUtils.copySpansFrom(text, 0, hiddenContent.length(),
TokenImageSpan.class, hiddenContent, 0);
hiddenContent.setSpan(spanWatcher, 0, hiddenContent.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
} else {
getText().setSpan(spanWatcher, 0, getText().length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
}
}
} else {
if (hiddenContent != null) {
setText(hiddenContent);
TextUtils.copySpansFrom(hiddenContent, 0, hiddenContent.length(),
TokenImageSpan.class, getText(), 0);
hiddenContent = null;
if (hintVisible) {
setSelection(prefix.length());
} else {
post(new Runnable() {
@Override
public void run() {
setSelection(getText().length());
}
});
}
TokenSpanWatcher[] watchers = getText().getSpans(0, getText().length(), TokenSpanWatcher.class);
if (watchers.length == 0) {
//Span watchers can get removed in setText
getText().setSpan(spanWatcher, 0, getText().length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
}
}
}
internalEditInProgress = false;
}
@Override
public void onFocusChanged(boolean hasFocus, int direction, Rect previous) {
super.onFocusChanged(hasFocus, direction, previous);
// Clear sections when focus changes to avoid a token remaining selected
clearSelections();
// Collapse the view to a single line
if (allowCollapse) performCollapse(hasFocus);
}
@SuppressWarnings("unchecked cast")
@Override
protected CharSequence convertSelectionToString(Object object) {
selectedObject = (T) object;
return "";
}
protected TokenImageSpan buildSpanForObject(T obj) {
if (obj == null) {
return null;
}
View tokenView = getViewForObject(obj);
return new TokenImageSpan(tokenView, obj);
}
@Override
protected void replaceText(CharSequence ignore) {
clearComposingText();
// Don't build a token for an empty String
if (selectedObject == null || selectedObject.toString().equals("")) return;
TokenImageSpan tokenSpan = buildSpanForObject(selectedObject);
Editable editable = getText();
Range candidateRange = getCurrentCandidateTokenRange();
String original = TextUtils.substring(editable, candidateRange.start, candidateRange.end);
//Keep track of replacements for a bug workaround
if (original.length() > 0) {
lastCompletionText = original;
}
if (editable != null) {
internalEditInProgress = true;
if (tokenSpan == null) {
editable.replace(candidateRange.start, candidateRange.end, "");
} else if (shouldIgnoreToken(tokenSpan.getToken())) {
editable.replace(candidateRange.start, candidateRange.end, "");
if (listener != null) {
listener.onTokenIgnored(tokenSpan.getToken());
}
} else {
SpannableStringBuilder ssb = new SpannableStringBuilder(tokenizer.wrapTokenValue(tokenToString(tokenSpan.token)));
editable.replace(candidateRange.start, candidateRange.end, ssb);
editable.setSpan(tokenSpan, candidateRange.start, candidateRange.start + ssb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
editable.insert(candidateRange.start + ssb.length(), " ");
}
internalEditInProgress = false;
}
}
@Override
public boolean extractText(@NonNull ExtractedTextRequest request, @NonNull ExtractedText outText) {
try {
return super.extractText(request, outText);
} catch (IndexOutOfBoundsException ex) {
Log.d(TAG, "extractText hit IndexOutOfBoundsException. This may be normal.", ex);
return false;
}
}
/**
* Append a token object to the object list. May only be called from the main thread.
*
* @param object the object to add to the displayed tokens
*/
@UiThread
public void addObjectSync(T object) {
if (object == null) return;
if (shouldIgnoreToken(object)) {
if (listener != null) {
listener.onTokenIgnored(object);
}
return;
}
if (tokenLimit != -1 && getObjects().size() == tokenLimit) return;
insertSpan(buildSpanForObject(object));
if (getText() != null && isFocused()) setSelection(getText().length());
}
/**
* Append a token object to the object list. Object will be added on the main thread.
*
* @param object the object to add to the displayed tokens
*/
public void addObjectAsync(final T object) {
post(new Runnable() {
@Override
public void run() {
addObjectSync(object);
}
});
}
/**
* Remove an object from the token list. Will remove duplicates if present or do nothing if no
* object is present in the view. Uses {@link Object#equals(Object)} to find objects. May only
* be called from the main thread
*
* @param object object to remove, may be null or not in the view
*/
@UiThread
public void removeObjectSync(T object) {
//To make sure all the appropriate callbacks happen, we just want to piggyback on the
//existing code that handles deleting spans when the text changes
ArrayList<Editable> texts = new ArrayList<>();
//If there is hidden content, it's important that we update it first
if (hiddenContent != null) {
texts.add(hiddenContent);
}
if (getText() != null) {
texts.add(getText());
}
// If the object is currently visible, remove it
for (Editable text : texts) {
TokenImageSpan[] spans = text.getSpans(0, text.length(), TokenImageSpan.class);
for (TokenImageSpan span : spans) {
if (span.getToken().equals(object)) {
removeSpan(text, span);
}
}
}
updateCountSpan();
}
/**
* Remove an object from the token list. Will remove duplicates if present or do nothing if no
* object is present in the view. Uses {@link Object#equals(Object)} to find objects. Object
* will be added on the main thread
*
* @param object object to remove, may be null or not in the view
*/
public void removeObjectAsync(final T object) {
post(new Runnable() {
@Override
public void run() {
removeObjectSync(object);
}
});
}
/**
* Remove all objects from the token list. Objects will be removed on the main thread.
*/
public void clearAsync() {
post(new Runnable() {
@Override
public void run() {
for (T object : getObjects()) {
removeObjectSync(object);
}
}
});
}
/**
* Set the count span the current number of hidden objects
*/