-
Notifications
You must be signed in to change notification settings - Fork 384
Expand file tree
/
Copy pathTokenCompleteTextView.java
More file actions
1577 lines (1365 loc) · 56.1 KB
/
TokenCompleteTextView.java
File metadata and controls
1577 lines (1365 loc) · 56.1 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.annotation.TargetApi;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Layout;
import android.text.NoCopySpan;
import android.text.Selection;
import android.text.SpanWatcher;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.QwertyKeyListener;
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.EditorInfo;
import android.view.inputmethod.ExtractedText;
import android.view.inputmethod.ExtractedTextRequest;
import android.view.inputmethod.InputConnection;
import android.view.inputmethod.InputConnectionWrapper;
import android.view.inputmethod.InputMethodManager;
import android.widget.Filter;
import android.widget.ListView;
import android.widget.MultiAutoCompleteTextView;
import android.widget.TextView;
import java.io.Serializable;
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 MultiAutoCompleteTextView implements TextView.OnEditorActionListener {
//Logging
public static final String TAG = "TokenAutoComplete";
//When the token is deleted...
public enum TokenDeleteStyle {
_Parent, //...do the parent behavior, not recommended
Clear, //...clear the underlying text
PartialCompletion, //...return the original text used for completion
ToString, //...replace the token with toString of the token object
SelectThenDelete //...first backspace selects the token and another backspace deletes it
}
//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 = false;
TokenClickStyle(final boolean selectable) {
mIsSelectable = selectable;
}
public boolean isSelectable() {
return mIsSelectable;
}
}
private char[] splitChar = {',', ';'};
private Tokenizer tokenizer;
private T selectedObject;
private TokenListener<T> listener;
private TokenSpanWatcher spanWatcher;
private TokenTextWatcher textWatcher;
private ArrayList<T> objects;
private List<TokenCompleteTextView<T>.TokenImageSpan> hiddenSpans;
private TokenDeleteStyle deletionStyle = TokenDeleteStyle._Parent;
private TokenClickStyle tokenClickStyle = TokenClickStyle.None;
private CharSequence prefix = "";
private boolean hintVisible = false;
private Layout lastLayout = null;
private boolean allowDuplicates = true;
private boolean focusChanging = false;
private boolean initialized = false;
private boolean performBestGuess = true;
private boolean savingState = false;
private boolean shouldFocusNext = false;
private boolean allowCollapse = true;
private int tokenLimit = -1;
/**
* 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 MultiAutoCompleteTextView.CommaTokenizer());
objects = new ArrayList<>();
Editable text = getText();
assert null != text;
spanWatcher = new TokenSpanWatcher();
textWatcher = new TokenTextWatcher();
hiddenSpans = new ArrayList<>();
// Initialise TextChangedListeners
addListeners();
setTextIsSelectable(false);
setLongClickable(false);
//In theory, get the soft keyboard to not supply suggestions. very unreliable < API 11
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 textfilter (listens for the splitchars)
setFilters(new InputFilter[]{new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
// Token limit check
if (tokenLimit != -1 && objects.size() == tokenLimit) {
return "";
} else if (source.length() == 1) {//Detect split characters, remove them and complete the current token instead
if (isSplitChar(source.charAt(0))) {
performCompletion();
return "";
}
}
//We need to not do anything when we would delete the prefix
if (dstart < prefix.length()) {
//when settext is called, which should only be called during
//restoring, dstart and dend 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 (dstart == 0 && dend == 0) {
return null;
} else if (dend <= prefix.length()) {
//Don't do anything
return prefix.subSequence(dstart, dend);
} else {
//Delete everything up to the prefix
return prefix.subSequence(dstart, prefix.length());
}
}
return null;
}
}});
//We had _Parent style during initialization to handle an edge case in the parent
//now we can switch to Clear, usually the best choice
setDeletionStyle(TokenDeleteStyle.Clear);
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(@NonNull CharSequence text, int start, int end,
int keyCode) {
if (start < prefix.length()) {
start = prefix.length();
}
Filter filter = getFilter();
if (filter != null) {
if (hintVisible) {
filter.filter("");
} else {
filter.filter(text.subSequence(start, end), this);
}
}
}
@Override
public void setTokenizer(Tokenizer t) {
super.setTokenizer(t);
tokenizer = t;
}
/**
* Set the action to be taken when a Token is removed
*
* @param dStyle The TokenDeleteStyle
*/
public void setDeletionStyle(TokenDeleteStyle dStyle) {
deletionStyle = dStyle;
}
/**
* Set the action to be taken when a Token is clicked
*
* @param cStyle The TokenClickStyle
*/
@SuppressWarnings("unused")
public void setTokenClickStyle(TokenClickStyle cStyle) {
tokenClickStyle = cStyle;
}
/**
* Set the listener that will be notified of changes in the Tokenlist
*
* @param l The TokenListener
*/
public void setTokenListener(TokenListener<T> l) {
listener = l;
}
/**
* 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.
*/
@SuppressWarnings("unused")
public boolean isTokenRemovable(T token) {
return true;
}
/**
* 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
prefix = "";
Editable text = getText();
if (text != null) {
text.insert(0, p);
}
prefix = p;
updateHint();
}
/**
* Get the list of Tokens
*
* @return List of tokens
*/
public List<T> getObjects() {
return objects;
}
/**
* Set a list of characters that should trigger the token creation
* Because spaces are difficult to handle, we add '§' as an additional splitChar
*
* @param splitChar char[] with a characters that trigger the token creation
*/
public void setSplitChar(char[] splitChar) {
char[] fixed = splitChar;
if (splitChar[0] == ' ') {
fixed = new char[splitChar.length + 1];
fixed[0] = '§';
System.arraycopy(splitChar, 0, fixed, 1, splitChar.length);
}
this.splitChar = fixed;
// Keep the tokenizer and splitchars in sync
this.setTokenizer(new CharacterTokenizer(splitChar));
}
/**
* Sets a single character to trigger the token creation
*
* @param splitChar char that triggers the token creation
*/
@SuppressWarnings("unused")
public void setSplitChar(char splitChar) {
setSplitChar(new char[]{splitChar});
}
/**
* Returns true if the character is currently configured as a splitChar
*
* @param c the char to test
* @return boolean
*/
private boolean isSplitChar(char c) {
for (char split : splitChar) {
if (c == split) return true;
}
return false;
}
/**
* Sets whether to allow duplicate objects. If false, when the user selects
* an object that's already in the view, the current text is just cleared.
* <br>
* Defaults to true. Requires that the objects implement equals() correctly.
*
* @param allow boolean
*/
@SuppressWarnings("unused")
public void allowDuplicates(boolean allow) {
allowDuplicates = allow;
}
/**
* Set whether we try to guess an entry from the autocomplete spinner or allow any text to be
* entered
*
* @param guess true to enable guessing
*/
@SuppressWarnings("unused")
public void performBestGuess(boolean guess) {
performBestGuess = guess;
}
/**
* Set whether the view should collapse to a single line when it loses focus.
*
* @param allowCollapse true if it should collapse
*/
@SuppressWarnings("unused")
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
*/
abstract protected T defaultObject(String completionText);
/**
* Correctly build accessibility string for token contents
*
* 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.terminateToken(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;
}
@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 int getCorrectedTokenEnd() {
Editable editable = getText();
int cursorPosition = getSelectionEnd();
return tokenizer.findTokenEnd(editable, cursorPosition);
}
private int getCorrectedTokenBeginning(int end) {
int start = tokenizer.findTokenStart(getText(), end);
if (start < prefix.length()) {
start = prefix.length();
}
return start;
}
protected String currentCompletionText() {
if (hintVisible) return ""; //Can't have any text if the hint is visible
Editable editable = getText();
int end = getCorrectedTokenEnd();
int start = getCorrectedTokenBeginning(end);
//Some keyboards add extra spaces when doing corrections, so
return TextUtils.substring(editable, start, end);
}
protected float maxTextWidth() {
return getWidth() - getPaddingLeft() - getPaddingRight();
}
boolean inInvalidate = false;
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private void api16Invalidate() {
if (initialized && !inInvalidate) {
inInvalidate = true;
setShadowLayer(getShadowRadius(), getShadowDx(), getShadowDy(), getShadowColor());
inInvalidate = false;
}
}
@Override
public void invalidate() {
//Need to force the TextView private mEditor variable to reset as well on API 16 and up
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
api16Invalidate();
}
super.invalidate();
}
@Override
public boolean enoughToFilter() {
if (tokenizer == null || hintVisible) {
return false;
}
int cursorPosition = getSelectionEnd();
if (cursorPosition < 0) {
return false;
}
int end = getCorrectedTokenEnd();
int start = getCorrectedTokenBeginning(end);
//Don't allow 0 length entries to filter
return end - start >= 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);
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(false);
break;
}
return handled || super.onKeyDown(keyCode, event);
}
private boolean deleteSelectedObject(boolean handled) {
if (tokenClickStyle != null && tokenClickStyle.isSelectable()) {
Editable text = getText();
if (text == null) return handled;
TokenImageSpan[] spans = text.getSpans(0, text.length(), TokenImageSpan.class);
for (TokenImageSpan span : spans) {
if (span.view.isSelected()) {
removeSpan(span);
handled = true;
break;
}
}
}
return handled;
}
@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) {
// Pause the spanwatcher
focusChanging = true;
if (!hasFocus) {
Editable text = getText();
if (text != null && lastLayout != null) {
// Display +x thingy if appropriate
int lastPosition = lastLayout.getLineVisibleEnd(0);
TokenImageSpan[] tokens = text.getSpans(0, lastPosition, TokenImageSpan.class);
int count = objects.size() - tokens.length;
// Make sure we don't add more than 1 CountSpan
CountSpan[] countSpans = text.getSpans(0, lastPosition, CountSpan.class);
if (count > 0 && countSpans.length == 0) {
lastPosition++;
CountSpan cs = new CountSpan(count, getContext(), getCurrentTextColor(),
(int) getTextSize(), (int) maxTextWidth());
text.insert(lastPosition, cs.text);
float newWidth = Layout.getDesiredWidth(text, 0,
lastPosition + cs.text.length(), lastLayout.getPaint());
//If the +x span will be moved off screen, move it one token in
if (newWidth > maxTextWidth()) {
text.delete(lastPosition, lastPosition + cs.text.length());
if (tokens.length > 0) {
TokenImageSpan token = tokens[tokens.length - 1];
lastPosition = text.getSpanStart(token);
cs.setCount(count + 1);
} else {
lastPosition = prefix.length();
}
text.insert(lastPosition, cs.text);
}
text.setSpan(cs, lastPosition, lastPosition + cs.text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
// Remove all spans behind the count span and hold them in the hiddenSpans List
// The generic type information is not captured in TokenImageSpan.class so we have
// to perform a cast for the returned spans to coerce them to the proper generic type.
hiddenSpans = new ArrayList<>(Arrays.asList(
(TokenImageSpan[]) text.getSpans(lastPosition + cs.text.length(), text.length(), TokenImageSpan.class)));
for (TokenImageSpan span : hiddenSpans) {
removeSpan(span);
}
}
}
} else {
final Editable text = getText();
if (text != null) {
CountSpan[] counts = text.getSpans(0, text.length(), CountSpan.class);
for (CountSpan count : counts) {
text.delete(text.getSpanStart(count), text.getSpanEnd(count));
text.removeSpan(count);
}
// Restore the spans we have hidden
for (TokenImageSpan span : hiddenSpans) {
insertSpan(span);
}
hiddenSpans.clear();
if (hintVisible) {
setSelection(prefix.length());
} else {
// Slightly delay moving the cursor to the end. Inserting spans seems to take
// some time. (ugly, but what can you do :( )
postDelayed(new Runnable() {
@Override
public void run() {
setSelection(text.length());
}
}, 10);
}
TokenSpanWatcher[] watchers = getText().getSpans(0, getText().length(), TokenSpanWatcher.class);
if (watchers.length == 0) {
//Someone removes watchers? I'm pretty sure this isn't in this code... -mgod
text.setSpan(spanWatcher, 0, text.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
}
}
}
// Start the spanwatcher
focusChanging = false;
}
@Override
public void onFocusChanged(boolean hasFocus, int direction, Rect previous) {
super.onFocusChanged(hasFocus, direction, previous);
// See if the user left any unfinished tokens and finish them
if (!hasFocus) performCompletion();
// Collapse the view to a single line
if (allowCollapse) performCollapse(hasFocus);
}
@SuppressWarnings("unchecked cast")
@Override
protected CharSequence convertSelectionToString(Object object) {
selectedObject = (T) object;
//if the token gets deleted, this text will get put in the field instead
switch (deletionStyle) {
case Clear:
case SelectThenDelete:
return "";
case PartialCompletion:
return currentCompletionText();
case ToString:
return object != null ? object.toString() : "";
case _Parent:
default:
return super.convertSelectionToString(object);
}
}
private SpannableStringBuilder buildSpannableForText(CharSequence text) {
//Add a sentinel , at the beginning so the user can remove an inner token and keep auto-completing
//This is a hack to work around the fact that the tokenizer cannot directly detect spans
//We don't want a space as the sentinel, and splitChar[0] is guaranteed to be something non-space
char sentinel = splitChar[0];
return new SpannableStringBuilder(String.valueOf(sentinel) + tokenizer.terminateToken(text));
}
protected TokenImageSpan buildSpanForObject(T obj) {
if (obj == null) {
return null;
}
View tokenView = getViewForObject(obj);
return new TokenImageSpan(tokenView, obj, (int) maxTextWidth());
}
@Override
protected void replaceText(CharSequence text) {
clearComposingText();
// Don't build a token for an empty String
if (selectedObject == null || selectedObject.toString().equals("")) return;
SpannableStringBuilder ssb = buildSpannableForText(text);
TokenImageSpan tokenSpan = buildSpanForObject(selectedObject);
Editable editable = getText();
int cursorPosition = getSelectionEnd();
int end = cursorPosition;
int start = cursorPosition;
if (!hintVisible) {
//If you force the drop down to show when the hint is visible, you can run a completion
//on the hint. If the hint includes commas, this truncates and inserts the hint in the field
end = getCorrectedTokenEnd();
start = getCorrectedTokenBeginning(end);
}
String original = TextUtils.substring(editable, start, end);
if (editable != null) {
if (tokenSpan == null) {
editable.replace(start, end, "");
} else if (!allowDuplicates && objects.contains(tokenSpan.getToken())) {
editable.replace(start, end, "");
} else {
QwertyKeyListener.markAsReplaced(editable, start, end, original);
editable.replace(start, end, ssb);
editable.setSpan(tokenSpan, start, start + ssb.length() - 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
}
@Override
public boolean extractText(@NonNull ExtractedTextRequest request, @NonNull ExtractedText outText) {
try {
return super.extractText(request, outText);
} catch (IndexOutOfBoundsException ignored) {
Log.d(TAG, "extractText hit IndexOutOfBoundsException. This may be normal.", ignored);
return false;
}
}
/**
* Append a token object to the object list
*
* @param object the object to add to the displayed tokens
* @param sourceText the text used if this object is deleted
*/
public void addObject(final T object, final CharSequence sourceText) {
post(new Runnable() {
@Override
public void run() {
if (object == null) return;
if (!allowDuplicates && objects.contains(object)) return;
if (tokenLimit != -1 && objects.size() == tokenLimit) return;
insertSpan(object, sourceText);
if (getText() != null && isFocused()) setSelection(getText().length());
}
});
}
/**
* Shorthand for addObject(object, "")
*
* @param object the object to add to the displayed token
*/
public void addObject(T object) {
addObject(object, "");
}
/**
* Remove an object from the token list. Will remove duplicates or do nothing if no object
* present in the view.
*
* @param object object to remove, may be null or not in the view
*/
public void removeObject(final T object) {
post(new Runnable() {
@Override
public void run() {
//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
Editable text = getText();
if (text == null) return;
// If the object is currently hidden, remove it
ArrayList<TokenImageSpan> toRemove = new ArrayList<>();
for (TokenImageSpan span : hiddenSpans) {
if (span.getToken().equals(object)) {
toRemove.add(span);
}
}
for (TokenImageSpan span : toRemove) {
hiddenSpans.remove(span);
// Remove it from the state and fire the callback
spanWatcher.onSpanRemoved(text, span, 0, 0);
}
updateCountSpan();
// If the object is currently visible, remove it
TokenImageSpan[] spans = text.getSpans(0, text.length(), TokenImageSpan.class);
for (TokenImageSpan span : spans) {
if (span.getToken().equals(object)) {
removeSpan(span);
}
}
}
});
}
/**
* Set the count span the current number of hidden objects
*/
private void updateCountSpan() {
Editable text = getText();
CountSpan[] counts = text.getSpans(0, text.length(), CountSpan.class);
int newCount = hiddenSpans.size();
for (CountSpan count : counts) {
if (newCount == 0) {
// No more hidden Objects: remove the CountSpan
text.delete(text.getSpanStart(count), text.getSpanEnd(count));
text.removeSpan(count);
} else {
// Update the CountSpan
count.setCount(hiddenSpans.size());
text.setSpan(count, text.getSpanStart(count), text.getSpanEnd(count), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}