-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
Copy pathMaterialAutoCompleteTextView.java
734 lines (647 loc) · 26.3 KB
/
MaterialAutoCompleteTextView.java
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
/*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.material.textfield;
import com.google.android.material.R;
import static com.google.android.material.theme.overlay.MaterialThemeOverlay.wrap;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.RippleDrawable;
import android.os.Parcel;
import android.os.Parcelable;
import androidx.appcompat.widget.AppCompatAutoCompleteTextView;
import androidx.appcompat.widget.ListPopupWindow;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewParent;
import android.view.accessibility.AccessibilityManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Filterable;
import android.widget.ListAdapter;
import android.widget.TextView;
import androidx.annotation.ArrayRes;
import androidx.annotation.ColorInt;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.android.material.color.MaterialColors;
import com.google.android.material.internal.ManufacturerUtils;
import com.google.android.material.internal.ThemeEnforcement;
import com.google.android.material.resources.MaterialResources;
import com.google.android.material.shape.MaterialShapeDrawable;
import java.util.List;
/**
* A special sub-class of {@link android.widget.AutoCompleteTextView} that is auto-inflated so that
* auto-complete text fields (e.g., for an Exposed Dropdown Menu) are accessible when being
* interacted through a screen reader.
*
* <p>The {@link ListPopupWindow} of the {@link android.widget.AutoCompleteTextView} is not modal,
* so it does not grab accessibility focus. The {@link MaterialAutoCompleteTextView} changes that by
* having a modal {@link ListPopupWindow} that is displayed instead of the non-modal one, so that
* the first item of the popup is automatically focused. This simulates the behavior of the {@link
* android.widget.Spinner}.
*/
public class MaterialAutoCompleteTextView extends AppCompatAutoCompleteTextView {
private static final int MAX_ITEMS_MEASURED = 15;
private static final String SWITCH_ACCESS_ACTIVITY_NAME = "SwitchAccess";
@NonNull private final ListPopupWindow modalListPopup;
@Nullable private final AccessibilityManager accessibilityManager;
@NonNull private final Rect tempRect = new Rect();
@LayoutRes private final int simpleItemLayout;
private final float popupElevation;
@Nullable private ColorStateList dropDownBackgroundTint;
private int simpleItemSelectedColor;
@Nullable private ColorStateList simpleItemSelectedRippleColor;
@Nullable private CharSequence selectedItem;
public MaterialAutoCompleteTextView(@NonNull Context context) {
this(context, null);
}
public MaterialAutoCompleteTextView(
@NonNull Context context, @Nullable AttributeSet attributeSet) {
this(context, attributeSet, R.attr.autoCompleteTextViewStyle);
}
public MaterialAutoCompleteTextView(
@NonNull Context context, @Nullable AttributeSet attributeSet, int defStyleAttr) {
super(wrap(context, attributeSet, defStyleAttr, 0), attributeSet, defStyleAttr);
// Ensure we are using the correctly themed context rather than the context that was passed in.
context = getContext();
TypedArray attributes =
ThemeEnforcement.obtainStyledAttributes(
context,
attributeSet,
R.styleable.MaterialAutoCompleteTextView,
defStyleAttr,
R.style.Widget_AppCompat_AutoCompleteTextView);
// Due to a framework bug, setting android:inputType="none" on xml has no effect. Therefore,
// we check it here in case the autoCompleteTextView should be non-editable.
if (attributes.hasValue(R.styleable.MaterialAutoCompleteTextView_android_inputType)) {
int inputType =
attributes.getInt(
R.styleable.MaterialAutoCompleteTextView_android_inputType, InputType.TYPE_NULL);
if (inputType == InputType.TYPE_NULL) {
setKeyListener(null);
}
}
simpleItemLayout =
attributes.getResourceId(
R.styleable.MaterialAutoCompleteTextView_simpleItemLayout,
R.layout.mtrl_auto_complete_simple_item);
popupElevation =
attributes.getDimensionPixelOffset(
R.styleable.MaterialAutoCompleteTextView_android_popupElevation,
R.dimen.mtrl_exposed_dropdown_menu_popup_elevation);
if (attributes.hasValue(R.styleable.MaterialAutoCompleteTextView_dropDownBackgroundTint)) {
dropDownBackgroundTint =
ColorStateList.valueOf(
attributes.getColor(
R.styleable.MaterialAutoCompleteTextView_dropDownBackgroundTint,
Color.TRANSPARENT));
}
simpleItemSelectedColor =
attributes.getColor(
R.styleable.MaterialAutoCompleteTextView_simpleItemSelectedColor, Color.TRANSPARENT);
simpleItemSelectedRippleColor =
MaterialResources.getColorStateList(
context,
attributes,
R.styleable.MaterialAutoCompleteTextView_simpleItemSelectedRippleColor);
accessibilityManager =
(AccessibilityManager) context.getSystemService(Context.ACCESSIBILITY_SERVICE);
modalListPopup = new ListPopupWindow(context);
modalListPopup.setModal(true);
modalListPopup.setAnchorView(this);
modalListPopup.setInputMethodMode(ListPopupWindow.INPUT_METHOD_NOT_NEEDED);
modalListPopup.setAdapter(getAdapter());
modalListPopup.setOnItemClickListener(
new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View selectedView, int position, long id) {
Object selectedItem =
position < 0 ? modalListPopup.getSelectedItem() : getAdapter().getItem(position);
setText(convertSelectionToString(selectedItem), false);
OnItemClickListener userOnItemClickListener = getOnItemClickListener();
if (userOnItemClickListener != null) {
if (selectedView == null || position < 0) {
selectedView = modalListPopup.getSelectedView();
position = modalListPopup.getSelectedItemPosition();
id = modalListPopup.getSelectedItemId();
}
userOnItemClickListener.onItemClick(
modalListPopup.getListView(), selectedView, position, id);
}
modalListPopup.dismiss();
}
});
if (attributes.hasValue(R.styleable.MaterialAutoCompleteTextView_simpleItems)) {
setSimpleItems(
attributes.getResourceId(R.styleable.MaterialAutoCompleteTextView_simpleItems, 0));
}
attributes.recycle();
// TODO: Remove this workaround once the framework bug (b/202873898) is fixed.
addTextChangedListener(
new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
@Override
public void afterTextChanged(Editable s) {
if (!TextUtils.equals(selectedItem, s)) {
selectedItem = null;
}
}
});
}
@Override
public void showDropDown() {
if (isPopupRequired()) {
modalListPopup.show();
} else {
super.showDropDown();
}
}
@Override
public void dismissDropDown() {
if (isPopupRequired()) {
modalListPopup.dismiss();
} else {
super.dismissDropDown();
}
}
@Override
public void onWindowFocusChanged(boolean hasWindowFocus) {
if (isPopupRequired()) {
// Do not dismissDropDown if touch exploration or switch access is enabled, in case the window
// lost focus in favor of the modalListPopup.
return;
}
super.onWindowFocusChanged(hasWindowFocus);
}
private boolean isPopupRequired() {
return isTouchExplorationEnabled() || isSwitchAccessEnabled();
}
private boolean isTouchExplorationEnabled() {
return accessibilityManager != null && accessibilityManager.isTouchExplorationEnabled();
}
private boolean isSwitchAccessEnabled() {
if (accessibilityManager == null || !accessibilityManager.isEnabled()) {
return false;
}
List<AccessibilityServiceInfo> accessibilityServiceInfos =
accessibilityManager.getEnabledAccessibilityServiceList(
AccessibilityServiceInfo.FEEDBACK_GENERIC);
if (accessibilityServiceInfos != null) {
for (AccessibilityServiceInfo info : accessibilityServiceInfos) {
if (info.getSettingsActivityName() != null
&& info.getSettingsActivityName().contains(SWITCH_ACCESS_ACTIVITY_NAME)) {
return true;
}
}
}
return false;
}
@Override
public <T extends ListAdapter & Filterable> void setAdapter(@Nullable T adapter) {
super.setAdapter(adapter);
modalListPopup.setAdapter(getAdapter());
}
@Override
public void setRawInputType(int type) {
super.setRawInputType(type);
onInputTypeChanged();
}
@Override
public void setOnItemSelectedListener(@Nullable OnItemSelectedListener listener) {
super.setOnItemSelectedListener(listener);
modalListPopup.setOnItemSelectedListener(getOnItemSelectedListener());
}
/**
* Sets the simple string items of auto-completion with the given string array resource. This
* method will create a default {@link ArrayAdapter} with a default item layout specified by
* {@code R.attr.simpleItemLayout} to display auto-complete items.
*
* @see #setSimpleItems(String[])
* @see #setAdapter(ListAdapter)
*/
public void setSimpleItems(@ArrayRes int stringArrayResId) {
setSimpleItems(getResources().getStringArray(stringArrayResId));
}
/**
* Sets the simple string items of auto-completion with the given string array. This method will
* create a default {@link ArrayAdapter} with a default item layout specified by
* {@code R.attr.simpleItemLayout} to display auto-complete items.
*
* @see #setSimpleItems(int)
* @see #setAdapter(ListAdapter)
*/
public void setSimpleItems(@NonNull String[] stringArray) {
setAdapter(new MaterialArrayAdapter<>(getContext(), simpleItemLayout, stringArray));
}
/**
* Sets the color of the popup dropdown container. It will take effect only if the popup
* background is a {@link MaterialShapeDrawable}, which is the default when using a Material
* theme.
*
* @param dropDownBackgroundColor the popup dropdown container color
* @see #setDropDownBackgroundTintList(ColorStateList)
* @see #getDropDownBackgroundTintList()
* @attr ref
* com.google.android.material.R.styleable#MaterialAutoCompleteTextView_dropDownBackgroundTint
*/
public void setDropDownBackgroundTint(@ColorInt int dropDownBackgroundColor) {
setDropDownBackgroundTintList(ColorStateList.valueOf(dropDownBackgroundColor));
}
/**
* Sets the color of the popup dropdown container. It will take effect only if the popup
* background is a {@link MaterialShapeDrawable}, which is the default when using a Material
* theme.
*
* @param dropDownBackgroundTint the popup dropdown container tint as a {@link ColorStateList}
* object.
* @see #setDropDownBackgroundTint(int)
* @see #getDropDownBackgroundTintList()
* @attr ref
* com.google.android.material.R.styleable#MaterialAutoCompleteTextView_dropDownBackgroundTint
*/
public void setDropDownBackgroundTintList(@Nullable ColorStateList dropDownBackgroundTint) {
this.dropDownBackgroundTint = dropDownBackgroundTint;
Drawable dropDownBackground = getDropDownBackground();
if (dropDownBackground instanceof MaterialShapeDrawable) {
((MaterialShapeDrawable) dropDownBackground).setFillColor(this.dropDownBackgroundTint);
}
}
/**
* Returns the color of the popup dropdown container.
*
* @see #setDropDownBackgroundTint(int)
* @see #setDropDownBackgroundTintList(ColorStateList)
* @attr ref
* com.google.android.material.R.styleable#MaterialAutoCompleteTextView_dropDownBackgroundTint
*/
@Nullable
public ColorStateList getDropDownBackgroundTintList() {
return dropDownBackgroundTint;
}
/**
* Sets the color of the default selected popup dropdown item to be used along with
* {@code R.attr.simpleItemLayout}.
*
* @param simpleItemSelectedColor the selected item color
* @see #getSimpleItemSelectedColor()
* @see #setSimpleItems(int)
* @attr ref
* com.google.android.material.R.styleable#MaterialAutoCompleteTextView_simpleItemSelectedColor
*/
public void setSimpleItemSelectedColor(int simpleItemSelectedColor) {
this.simpleItemSelectedColor = simpleItemSelectedColor;
if (getAdapter() instanceof MaterialArrayAdapter) {
((MaterialArrayAdapter) getAdapter()).updateSelectedItemColorStateList();
}
}
/**
* Returns the color of the default selected popup dropdown item.
*
* @see #setSimpleItemSelectedColor(int)
* @attr ref
* com.google.android.material.R.styleable#MaterialAutoCompleteTextView_simpleItemSelectedColor
*/
public int getSimpleItemSelectedColor() {
return simpleItemSelectedColor;
}
/**
* Sets the ripple color of the selected popup dropdown item to be used along with
* {@code R.attr.simpleItemLayout}.
*
* @param simpleItemSelectedRippleColor the ripple color state list
* @see #getSimpleItemSelectedRippleColor()
* @see #setSimpleItems(int)
* @attr ref
* com.google.android.material.R.styleable#MaterialAutoCompleteTextView_simpleItemSelectedRippleColor
*/
public void setSimpleItemSelectedRippleColor(
@Nullable ColorStateList simpleItemSelectedRippleColor) {
this.simpleItemSelectedRippleColor = simpleItemSelectedRippleColor;
if (getAdapter() instanceof MaterialArrayAdapter) {
((MaterialArrayAdapter) getAdapter()).updateSelectedItemColorStateList();
}
}
/**
* Returns the ripple color of the default selected popup dropdown item, or null if not set.
*
* @see #setSimpleItemSelectedRippleColor(ColorStateList)
* @attr ref
* com.google.android.material.R.styleable#MaterialAutoCompleteTextView_simpleItemSelectedRippleColor
*/
@Nullable
public ColorStateList getSimpleItemSelectedRippleColor() {
return simpleItemSelectedRippleColor;
}
@Override
public void setDropDownBackgroundDrawable(Drawable d) {
super.setDropDownBackgroundDrawable(d);
if (modalListPopup != null) {
modalListPopup.setBackgroundDrawable(d);
}
}
/**
* Returns the elevation of the dropdown popup.
*
* @attr ref
* com.google.android.material.R.styleable#MaterialAutoCompleteTextView_android_popupElevation
*/
public float getPopupElevation() {
return popupElevation;
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
// Meizu devices expect TextView#mHintLayout to be non-null if TextView#getHint() is non-null.
// In order to avoid crashing, we force the creation of the layout by setting an empty non-null
// hint.
TextInputLayout layout = findTextInputLayoutAncestor();
if (layout != null
&& layout.isProvidingHint()
&& super.getHint() == null
&& ManufacturerUtils.isMeizuDevice()) {
setHint("");
}
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
modalListPopup.dismiss();
}
@Nullable
@Override
public CharSequence getHint() {
// Certain test frameworks expect the actionable element to expose its hint as a label. Retrieve
// the hint from the TextInputLayout when it's providing it.
TextInputLayout textInputLayout = findTextInputLayoutAncestor();
if (textInputLayout != null && textInputLayout.isProvidingHint()) {
return textInputLayout.getHint();
}
return super.getHint();
}
@Override
public boolean getFreezesText() {
// Always return false to handle the input text restoration by ourselves. This is required
// to avoid the auto-completion from being updated when the view is recreated.
return false;
}
@Override
protected void replaceText(CharSequence text) {
selectedItem = text;
super.replaceText(text);
}
@Override
public void setText(CharSequence text, boolean filter) {
if (!filter) {
// When filter is false, the text is updated by the selection from the auto-complete list.
selectedItem = text;
}
super.setText(text, filter);
}
@Override
@NonNull
public Parcelable onSaveInstanceState() {
Parcelable parcelable = super.onSaveInstanceState();
if (TextUtils.isEmpty(getText()) || !super.getFreezesText()) {
return parcelable;
}
SavedState savedState = new SavedState(parcelable);
// Remember if the current text is from the auto-complete selection.
savedState.shouldRefreshAutoCompletion = (selectedItem == null);
savedState.inputText = getText();
return savedState;
}
@Override
public void onRestoreInstanceState(Parcelable state) {
if (!(state instanceof SavedState)) {
super.onRestoreInstanceState(state);
return;
}
SavedState savedState = (SavedState) state;
setText(savedState.inputText, savedState.shouldRefreshAutoCompletion);
super.onRestoreInstanceState(savedState.getSuperState());
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// Similar to a Spinner, make sure the view's width is at minimum the width of the largest
// dropdown item.
if (MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.AT_MOST) {
final int measuredWidth = getMeasuredWidth();
setMeasuredDimension(
Math.min(
Math.max(measuredWidth, measureContentWidth()),
MeasureSpec.getSize(widthMeasureSpec)),
getMeasuredHeight());
}
}
private int measureContentWidth() {
ListAdapter adapter = getAdapter();
TextInputLayout textInputLayout = findTextInputLayoutAncestor();
if (adapter == null || textInputLayout == null) {
return 0;
}
int width = 0;
View itemView = null;
int itemType = 0;
final int widthMeasureSpec =
MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.UNSPECIFIED);
final int heightMeasureSpec =
MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.UNSPECIFIED);
// Cap the number of items that will be measured.
int start = Math.max(0, modalListPopup.getSelectedItemPosition());
final int end = Math.min(adapter.getCount(), start + MAX_ITEMS_MEASURED);
start = Math.max(0, end - MAX_ITEMS_MEASURED);
for (int i = start; i < end; i++) {
final int positionType = adapter.getItemViewType(i);
if (positionType != itemType) {
itemType = positionType;
itemView = null;
}
itemView = adapter.getView(i, itemView, textInputLayout);
if (itemView.getLayoutParams() == null) {
itemView.setLayoutParams(new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
}
itemView.measure(widthMeasureSpec, heightMeasureSpec);
width = Math.max(width, itemView.getMeasuredWidth());
}
// Add background padding to measured width.
Drawable background = modalListPopup.getBackground();
if (background != null) {
background.getPadding(tempRect);
width += tempRect.left + tempRect.right;
}
// Add icon width to measured width.
int iconWidth = textInputLayout.getEndIconView().getMeasuredWidth();
width += iconWidth;
return width;
}
private void onInputTypeChanged() {
TextInputLayout textInputLayout = findTextInputLayoutAncestor();
if (textInputLayout != null) {
textInputLayout.updateEditTextBoxBackgroundIfNeeded();
}
}
@Nullable
private TextInputLayout findTextInputLayoutAncestor() {
ViewParent parent = getParent();
while (parent != null) {
if (parent instanceof TextInputLayout) {
return (TextInputLayout) parent;
}
parent = parent.getParent();
}
return null;
}
/** ArrayAdapter for the {@link MaterialAutoCompleteTextView}. */
private class MaterialArrayAdapter<T> extends ArrayAdapter<String> {
@Nullable private ColorStateList selectedItemRippleOverlaidColor;
@Nullable private ColorStateList pressedRippleColor;
MaterialArrayAdapter(
@NonNull Context context, int resource, @NonNull String[] objects) {
super(context, resource, objects);
updateSelectedItemColorStateList();
}
void updateSelectedItemColorStateList() {
pressedRippleColor = sanitizeDropdownItemSelectedRippleColor();
selectedItemRippleOverlaidColor = createItemSelectedColorStateList();
}
@Override
public View getView(int position, @Nullable View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
if (view instanceof TextView) {
TextView textView = (TextView) view;
boolean isSelectedItem = getText().toString().contentEquals(textView.getText());
textView.setBackground(isSelectedItem ? getSelectedItemDrawable() : null);
}
return view;
}
@Nullable
private Drawable getSelectedItemDrawable() {
if (!hasSelectedColor()) {
return null;
}
// The adapter calls getView with the same position multiple times with different views,
// meaning we can't know which view is actually being used to show the list item. We need to
// create the drawable on every call, otherwise there can be a race condition causing the
// background color to not be updated to the right state.
Drawable colorDrawable = new ColorDrawable(simpleItemSelectedColor);
if (pressedRippleColor != null) {
// The ListPopupWindow takes over the states of its list items in order to implement its
// own ripple. That makes the RippleDrawable not work as expected, i.e. it will respond to
// pressed states, but not to other states like focused and hovered. To solve that, we
// create the selectedItemRippleOverlaidColor that will work in those missing states, making
// the selected list item stateful as expected.
colorDrawable.setTintList(selectedItemRippleOverlaidColor);
return new RippleDrawable(pressedRippleColor, colorDrawable, null);
} else {
return colorDrawable;
}
}
@Nullable
private ColorStateList createItemSelectedColorStateList() {
if (!hasSelectedColor() || !hasSelectedRippleColor()) {
return null;
}
int[] stateHovered = new int[] {android.R.attr.state_hovered, -android.R.attr.state_pressed};
int[] stateSelected =
new int[] {android.R.attr.state_selected, -android.R.attr.state_pressed};
int colorSelected =
simpleItemSelectedRippleColor.getColorForState(stateSelected, Color.TRANSPARENT);
int colorHovered =
simpleItemSelectedRippleColor.getColorForState(stateHovered, Color.TRANSPARENT);
// Use ripple colors overlaid over selected color.
int[] colors =
new int[] {
MaterialColors.layer(simpleItemSelectedColor, colorSelected),
MaterialColors.layer(simpleItemSelectedColor, colorHovered),
simpleItemSelectedColor
};
int[][] states = new int[][] {stateSelected, stateHovered, new int[] {}};
return new ColorStateList(states, colors);
}
private ColorStateList sanitizeDropdownItemSelectedRippleColor() {
if (!hasSelectedRippleColor()) {
return null;
}
// We need to ensure that the ripple drawable we create will show a color only for the pressed
// state so that the final ripple over the item view will be the correct color.
int[] statePressed = new int[] {android.R.attr.state_pressed};
int[] colors =
new int[] {
simpleItemSelectedRippleColor.getColorForState(statePressed, Color.TRANSPARENT),
Color.TRANSPARENT
};
int[][] states = new int[][] {statePressed, new int[] {}};
return new ColorStateList(states, colors);
}
private boolean hasSelectedColor() {
return simpleItemSelectedColor != Color.TRANSPARENT;
}
private boolean hasSelectedRippleColor() {
return simpleItemSelectedRippleColor != null;
}
}
private static final class SavedState extends BaseSavedState {
private boolean shouldRefreshAutoCompletion;
private CharSequence inputText;
public SavedState(Parcelable superState) {
super(superState);
}
public SavedState(Parcel source) {
super(source);
shouldRefreshAutoCompletion = source.readInt() != 0;
inputText = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source);
}
@Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeInt(shouldRefreshAutoCompletion ? 1 : 0);
TextUtils.writeToParcel(inputText, out, flags);
}
public static final Creator<SavedState> CREATOR =
new Creator<SavedState>() {
@Override
public SavedState createFromParcel(Parcel source) {
return new SavedState(source);
}
@Override
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
}