-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
SearchView.java
1115 lines (973 loc) · 38.8 KB
/
SearchView.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
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
/*
* Copyright 2022 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
*
* https://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.search;
import com.google.android.material.R;
import static androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP;
import static com.google.android.material.theme.overlay.MaterialThemeOverlay.wrap;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Parcel;
import android.os.Parcelable;
import androidx.appcompat.content.res.AppCompatResources;
import androidx.appcompat.graphics.drawable.DrawerArrowDrawable;
import androidx.appcompat.widget.Toolbar;
import androidx.appcompat.widget.Toolbar.OnMenuItemClickListener;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityEvent;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.TextView;
import androidx.activity.BackEventCompat;
import androidx.annotation.ColorInt;
import androidx.annotation.DrawableRes;
import androidx.annotation.MenuRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.Px;
import androidx.annotation.RequiresApi;
import androidx.annotation.RestrictTo;
import androidx.annotation.StringRes;
import androidx.annotation.StyleRes;
import androidx.annotation.VisibleForTesting;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.graphics.drawable.DrawableCompat;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.core.widget.TextViewCompat;
import androidx.customview.view.AbsSavedState;
import com.google.android.material.appbar.MaterialToolbar;
import com.google.android.material.color.MaterialColors;
import com.google.android.material.elevation.ElevationOverlayProvider;
import com.google.android.material.internal.ClippableRoundedCornerLayout;
import com.google.android.material.internal.ContextUtils;
import com.google.android.material.internal.FadeThroughDrawable;
import com.google.android.material.internal.ThemeEnforcement;
import com.google.android.material.internal.ToolbarUtils;
import com.google.android.material.internal.TouchObserverFrameLayout;
import com.google.android.material.internal.ViewUtils;
import com.google.android.material.motion.MaterialBackHandler;
import com.google.android.material.motion.MaterialBackOrchestrator;
import com.google.android.material.motion.MaterialMainContainerBackHelper;
import com.google.android.material.shape.MaterialShapeUtils;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
/**
* Layout that provides a full screen search view and can be used with {@link SearchBar}.
*
* <p>The example below shows how to use the {@link SearchBar} and {@link SearchView} together:
*
* <pre>
* <androidx.coordinatorlayout.widget.CoordinatorLayout
* android:layout_width="match_parent"
* android:layout_height="match_parent">
*
* <!-- NestedScrollingChild goes here (NestedScrollView, RecyclerView, etc.). -->
* <androidx.core.widget.NestedScrollView
* android:layout_width="match_parent"
* android:layout_height="match_parent"
* app:layout_behavior="@string/searchbar_scrolling_view_behavior">
* <!-- Screen content goes here. -->
* </androidx.core.widget.NestedScrollView>
*
* <com.google.android.material.appbar.AppBarLayout
* android:layout_width="match_parent"
* android:layout_height="wrap_content">
* <com.google.android.material.search.SearchBar
* android:id="@+id/search_bar"
* android:layout_width="match_parent"
* android:layout_height="wrap_content"
* android:hint="@string/searchbar_hint" />
* </com.google.android.material.appbar.AppBarLayout>
*
* <com.google.android.material.search.SearchView
* android:layout_width="match_parent"
* android:layout_height="match_parent"
* android:hint="@string/searchbar_hint"
* app:layout_anchor="@id/search_bar">
* <!-- Search suggestions/results go here (ScrollView, RecyclerView, etc.). -->
* </com.google.android.material.search.SearchView>
* </androidx.coordinatorlayout.widget.CoordinatorLayout>
* </pre>
*
* <p>For more information, see the <a
* href="https://github.com/material-components/material-components-android/blob/master/docs/components/Search.md">component
* developer guidance</a> and <a href="https://material.io/components/search/overview">design
* guidelines</a>.
*/
@SuppressWarnings("RestrictTo")
public class SearchView extends FrameLayout
implements CoordinatorLayout.AttachedBehavior, MaterialBackHandler {
private static final long TALKBACK_FOCUS_CHANGE_DELAY_MS = 100;
private static final int DEF_STYLE_RES = R.style.Widget_Material3_SearchView;
final View scrim;
final ClippableRoundedCornerLayout rootView;
final View backgroundView;
final View statusBarSpacer;
final FrameLayout headerContainer;
final FrameLayout toolbarContainer;
final MaterialToolbar toolbar;
final Toolbar dummyToolbar;
final TextView searchPrefix;
final EditText editText;
final ImageButton clearButton;
final View divider;
final TouchObserverFrameLayout contentContainer;
private final boolean layoutInflated;
private final SearchViewAnimationHelper searchViewAnimationHelper;
@NonNull
private final MaterialBackOrchestrator backOrchestrator = new MaterialBackOrchestrator(this);
private final boolean backHandlingEnabled;
private final ElevationOverlayProvider elevationOverlayProvider;
private final Set<TransitionListener> transitionListeners = new LinkedHashSet<>();
@Nullable private SearchBar searchBar;
private int softInputMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
private boolean animatedNavigationIcon;
private boolean animatedMenuItems;
private boolean autoShowKeyboard;
@ColorInt private final int backgroundColor;
private boolean useWindowInsetsController;
private boolean statusBarSpacerEnabledOverride;
@NonNull private TransitionState currentTransitionState = TransitionState.HIDDEN;
private Map<View, Integer> childImportantForAccessibilityMap;
public SearchView(@NonNull Context context) {
this(context, null);
}
public SearchView(@NonNull Context context, @Nullable AttributeSet attrs) {
this(context, attrs, R.attr.materialSearchViewStyle);
}
public SearchView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(wrap(context, attrs, defStyleAttr, DEF_STYLE_RES), attrs, defStyleAttr);
// Ensure we are using the correctly themed context rather than the context that was passed in.
context = getContext();
TypedArray a =
ThemeEnforcement.obtainStyledAttributes(
context, attrs, R.styleable.SearchView, defStyleAttr, DEF_STYLE_RES);
backgroundColor = a.getColor(R.styleable.SearchView_backgroundTint, 0);
int headerLayoutResId = a.getResourceId(R.styleable.SearchView_headerLayout, -1);
int textAppearanceResId = a.getResourceId(R.styleable.SearchView_android_textAppearance, -1);
String text = a.getString(R.styleable.SearchView_android_text);
String hint = a.getString(R.styleable.SearchView_android_hint);
String searchPrefixText = a.getString(R.styleable.SearchView_searchPrefixText);
boolean useDrawerArrowDrawable =
a.getBoolean(R.styleable.SearchView_useDrawerArrowDrawable, false);
animatedNavigationIcon = a.getBoolean(R.styleable.SearchView_animateNavigationIcon, true);
animatedMenuItems = a.getBoolean(R.styleable.SearchView_animateMenuItems, true);
boolean hideNavigationIcon = a.getBoolean(R.styleable.SearchView_hideNavigationIcon, false);
autoShowKeyboard = a.getBoolean(R.styleable.SearchView_autoShowKeyboard, true);
backHandlingEnabled = a.getBoolean(R.styleable.SearchView_backHandlingEnabled, true);
a.recycle();
LayoutInflater.from(context).inflate(R.layout.mtrl_search_view, this);
layoutInflated = true;
scrim = findViewById(R.id.open_search_view_scrim);
rootView = findViewById(R.id.open_search_view_root);
backgroundView = findViewById(R.id.open_search_view_background);
statusBarSpacer = findViewById(R.id.open_search_view_status_bar_spacer);
headerContainer = findViewById(R.id.open_search_view_header_container);
toolbarContainer = findViewById(R.id.open_search_view_toolbar_container);
toolbar = findViewById(R.id.open_search_view_toolbar);
dummyToolbar = findViewById(R.id.open_search_view_dummy_toolbar);
searchPrefix = findViewById(R.id.open_search_view_search_prefix);
editText = findViewById(R.id.open_search_view_edit_text);
clearButton = findViewById(R.id.open_search_view_clear_button);
divider = findViewById(R.id.open_search_view_divider);
contentContainer = findViewById(R.id.open_search_view_content_container);
searchViewAnimationHelper = new SearchViewAnimationHelper(this);
elevationOverlayProvider = new ElevationOverlayProvider(context);
setUpRootView();
setUpBackgroundViewElevationOverlay();
setUpHeaderLayout(headerLayoutResId);
setSearchPrefixText(searchPrefixText);
setUpEditText(textAppearanceResId, text, hint);
setUpBackButton(useDrawerArrowDrawable, hideNavigationIcon);
setUpClearButton();
setUpContentOnTouchListener();
setUpInsetListeners();
}
@Override
public void addView(View child, int index, ViewGroup.LayoutParams params) {
if (layoutInflated) {
contentContainer.addView(child, index, params);
} else {
super.addView(child, index, params);
}
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
updateSoftInputMode();
}
@RequiresApi(VERSION_CODES.LOLLIPOP)
@Override
public void setElevation(float elevation) {
super.setElevation(elevation);
setUpBackgroundViewElevationOverlay(elevation);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
MaterialShapeUtils.setParentAbsoluteElevation(this);
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
backOrchestrator.stopListeningForBackCallbacks();
}
@Override
@NonNull
public CoordinatorLayout.Behavior<SearchView> getBehavior() {
return new SearchView.Behavior();
}
@Override
public void startBackProgress(@NonNull BackEventCompat backEvent) {
if (isHiddenOrHiding() || searchBar == null) {
return;
}
searchViewAnimationHelper.startBackProgress(backEvent);
}
@Override
public void updateBackProgress(@NonNull BackEventCompat backEvent) {
if (isHiddenOrHiding()
|| searchBar == null
|| VERSION.SDK_INT < VERSION_CODES.UPSIDE_DOWN_CAKE) {
return;
}
searchViewAnimationHelper.updateBackProgress(backEvent);
}
@Override
public void handleBackInvoked() {
if (isHiddenOrHiding()) {
return;
}
BackEventCompat backEvent = searchViewAnimationHelper.onHandleBackInvoked();
if (VERSION.SDK_INT >= VERSION_CODES.UPSIDE_DOWN_CAKE
&& searchBar != null
&& backEvent != null) {
searchViewAnimationHelper.finishBackProgress();
} else {
hide();
}
}
@Override
public void cancelBackProgress() {
if (isHiddenOrHiding()
|| searchBar == null
|| VERSION.SDK_INT < VERSION_CODES.UPSIDE_DOWN_CAKE) {
return;
}
searchViewAnimationHelper.cancelBackProgress();
}
@VisibleForTesting
MaterialMainContainerBackHelper getBackHelper() {
return searchViewAnimationHelper.getBackHelper();
}
private boolean isHiddenOrHiding() {
return currentTransitionState.equals(TransitionState.HIDDEN)
|| currentTransitionState.equals(TransitionState.HIDING);
}
@Nullable
private Window getActivityWindow() {
Activity activity = ContextUtils.getActivity(getContext());
return activity == null ? null : activity.getWindow();
}
@SuppressLint("ClickableViewAccessibility") // Will be handled by accessibility delegate.
private void setUpRootView() {
rootView.setOnTouchListener((v, event) -> true);
}
private void setUpBackgroundViewElevationOverlay() {
setUpBackgroundViewElevationOverlay(getOverlayElevation());
}
private void setUpBackgroundViewElevationOverlay(float elevation) {
if (elevationOverlayProvider == null || backgroundView == null) {
return;
}
int backgroundColorWithOverlay =
elevationOverlayProvider.compositeOverlayIfNeeded(backgroundColor, elevation);
backgroundView.setBackgroundColor(backgroundColorWithOverlay);
}
private float getOverlayElevation() {
if (searchBar != null) {
return searchBar.getCompatElevation();
} else {
return getResources().getDimension(R.dimen.m3_searchview_elevation);
}
}
private void setUpHeaderLayout(int headerLayoutResId) {
if (headerLayoutResId != -1) {
View headerView =
LayoutInflater.from(getContext()).inflate(headerLayoutResId, headerContainer, false);
addHeaderView(headerView);
}
}
private void setUpEditText(@StyleRes int textAppearanceResId, String text, String hint) {
if (textAppearanceResId != -1) {
TextViewCompat.setTextAppearance(editText, textAppearanceResId);
}
editText.setText(text);
editText.setHint(hint);
}
private void setUpBackButton(boolean useDrawerArrowDrawable, boolean hideNavigationIcon) {
if (hideNavigationIcon) {
toolbar.setNavigationIcon(null);
return;
}
toolbar.setNavigationOnClickListener(v -> hide());
if (useDrawerArrowDrawable) {
DrawerArrowDrawable drawerArrowDrawable = new DrawerArrowDrawable(getContext());
drawerArrowDrawable.setColor(MaterialColors.getColor(this, R.attr.colorOnSurface));
toolbar.setNavigationIcon(drawerArrowDrawable);
}
}
private void setUpClearButton() {
clearButton.setOnClickListener(
v -> {
clearText();
requestFocusAndShowKeyboardIfNeeded();
});
editText.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) {
clearButton.setVisibility(s.length() > 0 ? VISIBLE : GONE);
}
@Override
public void afterTextChanged(Editable s) {}
});
}
@SuppressLint("ClickableViewAccessibility") // Will be handled by accessibility delegate.
private void setUpContentOnTouchListener() {
contentContainer.setOnTouchListener(
(v, event) -> {
if (isAdjustNothingSoftInputMode()) {
clearFocusAndHideKeyboard();
}
return false;
});
}
private void setUpStatusBarSpacer(@Px int height) {
if (statusBarSpacer.getLayoutParams().height != height) {
statusBarSpacer.getLayoutParams().height = height;
statusBarSpacer.requestLayout();
}
}
@Px
private int getStatusBarHeight() {
@SuppressLint({
"DiscouragedApi",
"InternalInsetResource"
}) // Used for initial value. A WindowInsetsListener will apply correct insets later.
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
return getResources().getDimensionPixelSize(resourceId);
} else {
return 0;
}
}
/**
* Note: DrawerArrowDrawable supports RTL, so there is no need to update the navigation icon for
* RTL if it is a DrawerArrowDrawable.
*/
private void updateNavigationIconIfNeeded() {
if (toolbar == null) {
return;
}
if (isNavigationIconDrawerArrowDrawable(toolbar)) {
return;
}
int navigationIcon = getDefaultNavigationIconResource();
if (searchBar == null) {
toolbar.setNavigationIcon(navigationIcon);
} else {
Drawable navigationIconDrawable =
DrawableCompat.wrap(
AppCompatResources.getDrawable(getContext(), navigationIcon).mutate());
if (toolbar.getNavigationIconTint() != null) {
DrawableCompat.setTint(navigationIconDrawable, toolbar.getNavigationIconTint());
}
DrawableCompat.setLayoutDirection(navigationIconDrawable, getLayoutDirection());
toolbar.setNavigationIcon(
new FadeThroughDrawable(searchBar.getNavigationIcon(), navigationIconDrawable));
updateNavigationIconProgressIfNeeded();
}
}
private boolean isNavigationIconDrawerArrowDrawable(@NonNull Toolbar toolbar) {
return DrawableCompat.unwrap(toolbar.getNavigationIcon()) instanceof DrawerArrowDrawable;
}
/**
* Listens to {@link WindowInsetsCompat} and adjusts layouts accordingly.
*
* <p><b>NOTE</b>: window insets are only delivered if no other layout consumed them before. E.g.:
*
* <ul>
* <li>by declaring {@code fitsSystemWindows=true}
* <li>by consuming insets via specific consume-methods (e.g. {@link
* WindowInsetsCompat#consumeSystemWindowInsets()}
* </ul>
*/
private void setUpInsetListeners() {
setUpToolbarInsetListener();
setUpDividerInsetListener();
setUpStatusBarSpacerInsetListener();
}
private void setUpToolbarInsetListener() {
ViewUtils.doOnApplyWindowInsets(
toolbar,
(view, insets, initialPadding) -> {
boolean isRtl = ViewUtils.isLayoutRtl(toolbar);
int paddingLeft = isRtl ? initialPadding.end : initialPadding.start;
int paddingRight = isRtl ? initialPadding.start : initialPadding.end;
toolbar.setPadding(
paddingLeft + insets.getSystemWindowInsetLeft(), initialPadding.top,
paddingRight + insets.getSystemWindowInsetRight(), initialPadding.bottom);
return insets;
});
}
private void setUpStatusBarSpacerInsetListener() {
// Set an initial height based on the default system value to support pre-L behavior.
setUpStatusBarSpacer(getStatusBarHeight());
// Listen to system window insets on L+ and adjusts status bar height based on the top inset.
ViewCompat.setOnApplyWindowInsetsListener(
statusBarSpacer,
(v, insets) -> {
int systemWindowInsetTop = insets.getSystemWindowInsetTop();
setUpStatusBarSpacer(systemWindowInsetTop);
if (!statusBarSpacerEnabledOverride) {
setStatusBarSpacerEnabledInternal(systemWindowInsetTop > 0);
}
return insets;
});
}
private void setUpDividerInsetListener() {
MarginLayoutParams layoutParams = (MarginLayoutParams) divider.getLayoutParams();
int leftMargin = layoutParams.leftMargin;
int rightMargin = layoutParams.rightMargin;
ViewCompat.setOnApplyWindowInsetsListener(
divider,
(v, insets) -> {
layoutParams.leftMargin = leftMargin + insets.getSystemWindowInsetLeft();
layoutParams.rightMargin = rightMargin + insets.getSystemWindowInsetRight();
return insets;
});
}
/** Returns whether or not this {@link SearchView} is set up with an {@link SearchBar}. */
public boolean isSetupWithSearchBar() {
return this.searchBar != null;
}
/**
* Sets up this {@link SearchView} with an {@link SearchBar}, which will result in the {@link
* SearchView} being shown when the {@link SearchBar} is clicked. This behavior will be set up
* automatically if the {@link SearchBar} and {@link SearchView} are in a {@link
* CoordinatorLayout} and the {@link SearchView} is anchored to the {@link SearchBar}.
*/
public void setupWithSearchBar(@Nullable SearchBar searchBar) {
this.searchBar = searchBar;
searchViewAnimationHelper.setSearchBar(searchBar);
if (searchBar != null) {
searchBar.setOnClickListener(v -> show());
if (VERSION.SDK_INT >= VERSION_CODES.UPSIDE_DOWN_CAKE) {
try {
searchBar.setHandwritingDelegatorCallback(this::show);
editText.setIsHandwritingDelegate(true);
} catch (LinkageError e) {
// Running on a device with an older build of Android U
// TODO(b/274154553): Remove try/catch block after Android U Beta 1 is released
}
}
}
updateNavigationIconIfNeeded();
setUpBackgroundViewElevationOverlay();
updateListeningForBackCallbacks(getCurrentTransitionState());
}
/**
* Add a header view to this {@link SearchView}, which will be placed above the search text area.
*
* <p>Note: due to complications with the expand/collapse animation, a header view is intended to
* be used with a standalone {@link SearchView} which slides up/down instead of morphing from an
* {@link SearchBar}.
*/
public void addHeaderView(@NonNull View headerView) {
headerContainer.addView(headerView);
headerContainer.setVisibility(VISIBLE);
}
/** Remove a header view from the section above the search text area. */
public void removeHeaderView(@NonNull View headerView) {
headerContainer.removeView(headerView);
if (headerContainer.getChildCount() == 0) {
headerContainer.setVisibility(GONE);
}
}
/** Remove all header views from the section above the search text area. */
public void removeAllHeaderViews() {
headerContainer.removeAllViews();
headerContainer.setVisibility(GONE);
}
/**
* Sets whether the navigation icon should be animated from the {@link SearchBar} to {@link
* SearchView}.
*/
public void setAnimatedNavigationIcon(boolean animatedNavigationIcon) {
this.animatedNavigationIcon = animatedNavigationIcon;
}
/**
* Returns whether the navigation icon should be animated from the {@link SearchBar} to {@link
* SearchView}.
*/
public boolean isAnimatedNavigationIcon() {
return animatedNavigationIcon;
}
/**
* Sets whether the menu items should be animated from the {@link SearchBar} to {@link
* SearchView}.
*/
public void setMenuItemsAnimated(boolean menuItemsAnimated) {
this.animatedMenuItems = menuItemsAnimated;
}
/**
* Returns whether the menu items should be animated from the {@link SearchBar} to {@link
* SearchView}.
*/
public boolean isMenuItemsAnimated() {
return animatedMenuItems;
}
/** Sets whether the soft keyboard should be shown when the {@link SearchView} is shown. */
public void setAutoShowKeyboard(boolean autoShowKeyboard) {
this.autoShowKeyboard = autoShowKeyboard;
}
/** Returns whether the soft keyboard should be shown when the {@link SearchView} is shown. */
public boolean isAutoShowKeyboard() {
return autoShowKeyboard;
}
/**
* Sets whether the soft keyboard should be shown with {@code WindowInsetsController}.
*
* @hide
*/
@RestrictTo(LIBRARY_GROUP)
public void setUseWindowInsetsController(boolean useWindowInsetsController) {
this.useWindowInsetsController = useWindowInsetsController;
}
/**
* Returns whether the soft keyboard should be shown with {@code WindowInsetsController}.
*
* @hide
*/
@RestrictTo(LIBRARY_GROUP)
public boolean isUseWindowInsetsController() {
return useWindowInsetsController;
}
/** Adds a listener to handle {@link SearchView} transitions such as showing and closing. */
public void addTransitionListener(@NonNull TransitionListener transitionListener) {
transitionListeners.add(transitionListener);
}
/** Removes a listener to handle {@link SearchView} transitions such as showing and closing. */
public void removeTransitionListener(@NonNull TransitionListener transitionListener) {
transitionListeners.remove(transitionListener);
}
/** Inflate a menu to provide additional options. */
public void inflateMenu(@MenuRes int menuResId) {
toolbar.inflateMenu(menuResId);
}
/** Set a listener to handle menu item clicks. */
public void setOnMenuItemClickListener(
@Nullable OnMenuItemClickListener onMenuItemClickListener) {
toolbar.setOnMenuItemClickListener(onMenuItemClickListener);
}
/** Returns the search prefix {@link TextView}, which appears before the main {@link EditText}. */
@NonNull
public TextView getSearchPrefix() {
return searchPrefix;
}
/** Sets the search prefix text. */
public void setSearchPrefixText(@Nullable CharSequence searchPrefixText) {
searchPrefix.setText(searchPrefixText);
searchPrefix.setVisibility(TextUtils.isEmpty(searchPrefixText) ? GONE : VISIBLE);
}
/** Returns the search prefix text. */
@Nullable
public CharSequence getSearchPrefixText() {
return searchPrefix.getText();
}
/** Returns the {@link Toolbar} used by the {@link SearchView}. */
@NonNull
public Toolbar getToolbar() {
return toolbar;
}
/** Returns the main {@link EditText} which can be used for hint and search text. */
@NonNull
public EditText getEditText() {
return editText;
}
/** Returns the text of main {@link EditText}, which usually represents the search text. */
@SuppressLint("KotlinPropertyAccess") // Editable extends CharSequence.
@NonNull // EditText never returns null after initialization.
public Editable getText() {
return editText.getText();
}
/** Sets the text of main {@link EditText}. */
@SuppressLint("KotlinPropertyAccess") // Editable extends CharSequence.
public void setText(@Nullable CharSequence text) {
editText.setText(text);
}
/** Sets the text of main {@link EditText}. */
public void setText(@StringRes int textResId) {
editText.setText(textResId);
}
/** Clears the text of main {@link EditText}. */
public void clearText() {
editText.setText("");
}
/** Returns the hint of main {@link EditText}. */
@Nullable
public CharSequence getHint() {
return editText.getHint();
}
/** Sets the hint of main {@link EditText}. */
public void setHint(@Nullable CharSequence hint) {
editText.setHint(hint);
}
/** Sets the hint of main {@link EditText}. */
public void setHint(@StringRes int hintResId) {
editText.setHint(hintResId);
}
/** Returns the current value of this {@link SearchView}'s soft input mode. */
@SuppressLint("KotlinPropertyAccess") // This is a not property.
public int getSoftInputMode() {
return softInputMode;
}
/**
* Sets the soft input mode for this {@link SearchView}. This is important because the {@link
* SearchView} will use this to determine whether the keyboard should be shown/hidden at the same
* time as the expand/collapse animation, or if the keyboard should be staggered with the
* animation to avoid glitchiness due to a resize of the screen. This will be set automatically by
* the {@link SearchView} during initial render but make sure to invoke this if you are changing
* the soft input mode at runtime.
*/
public void updateSoftInputMode() {
Window window = getActivityWindow();
if (window != null) {
this.softInputMode = window.getAttributes().softInputMode;
}
}
/**
* Enables/disables the status bar spacer, which can be used in cases where the status bar is
* translucent and the {@link SearchView} should not overlap the status bar area. This will be set
* automatically by the {@link SearchView} during initial render, but make sure to invoke this if
* you would like to override the default behavior.
*
* @hide
*/
@RestrictTo(LIBRARY_GROUP)
public void setStatusBarSpacerEnabled(boolean enabled) {
statusBarSpacerEnabledOverride = true;
setStatusBarSpacerEnabledInternal(enabled);
}
private void setStatusBarSpacerEnabledInternal(boolean enabled) {
statusBarSpacer.setVisibility(enabled ? VISIBLE : GONE);
}
/** Returns the current {@link TransitionState} for this {@link SearchView}. */
@NonNull
public TransitionState getCurrentTransitionState() {
return currentTransitionState;
}
void setTransitionState(@NonNull TransitionState state) {
setTransitionState(state, /* updateModalForAccessibility= */ true);
}
private void setTransitionState(
@NonNull TransitionState state, boolean updateModalForAccessibility) {
if (currentTransitionState.equals(state)) {
return;
}
if (updateModalForAccessibility) {
if (state == TransitionState.SHOWN) {
setModalForAccessibility(true);
} else if (state == TransitionState.HIDDEN) {
setModalForAccessibility(false);
}
}
TransitionState previousState = currentTransitionState;
currentTransitionState = state;
Set<TransitionListener> listeners = new LinkedHashSet<>(transitionListeners);
for (TransitionListener listener : listeners) {
listener.onStateChanged(this, previousState, state);
}
updateListeningForBackCallbacks(state);
}
private void updateListeningForBackCallbacks(@NonNull TransitionState state) {
// Only automatically handle back if we have a search bar to collapse to, and if back handling
// is enabled for the SearchView.
if (searchBar != null && backHandlingEnabled) {
if (state.equals(TransitionState.SHOWN)) {
backOrchestrator.startListeningForBackCallbacks();
} else if (state.equals(TransitionState.HIDDEN)) {
backOrchestrator.stopListeningForBackCallbacks();
}
}
}
/** Returns whether the {@link SearchView}'s main content view is shown or showing. */
public boolean isShowing() {
return currentTransitionState.equals(TransitionState.SHOWN)
|| currentTransitionState.equals(TransitionState.SHOWING);
}
/**
* Shows the {@link SearchView} with an animation.
*
* <p>Note: the show animation will not be started if the {@link SearchView} is currently shown or
* showing.
*/
public void show() {
if (currentTransitionState.equals(TransitionState.SHOWN)
|| currentTransitionState.equals(TransitionState.SHOWING)) {
return;
}
searchViewAnimationHelper.show();
}
/**
* Hides the {@link SearchView} with an animation.
*
* <p>Note: the hide animation will not be started if the {@link SearchView} is currently hidden
* or hiding.
*/
public void hide() {
if (currentTransitionState.equals(TransitionState.HIDDEN)
|| currentTransitionState.equals(TransitionState.HIDING)) {
return;
}
searchViewAnimationHelper.hide();
}
/** Updates the visibility of the {@link SearchView} without an animation. */
public void setVisible(boolean visible) {
boolean wasVisible = rootView.getVisibility() == VISIBLE;
rootView.setVisibility(visible ? VISIBLE : GONE);
updateNavigationIconProgressIfNeeded();
setTransitionState(
visible ? TransitionState.SHOWN : TransitionState.HIDDEN,
/* updateModalForAccessibility= */ wasVisible != visible);
}
private void updateNavigationIconProgressIfNeeded() {
ImageButton backButton = ToolbarUtils.getNavigationIconButton(toolbar);
if (backButton == null) {
return;
}
int progress = rootView.getVisibility() == VISIBLE ? 1 : 0;
Drawable drawable = DrawableCompat.unwrap(backButton.getDrawable());
if (drawable instanceof DrawerArrowDrawable) {
((DrawerArrowDrawable) drawable).setProgress(progress);
}
if (drawable instanceof FadeThroughDrawable) {
((FadeThroughDrawable) drawable).setProgress(progress);
}
}
/**
* Requests focus on the main {@link EditText} and shows the soft keyboard if automatic showing of
* the keyboard is enabled.
*/
void requestFocusAndShowKeyboardIfNeeded() {
if (autoShowKeyboard) {
requestFocusAndShowKeyboard();
}
}
/** Requests focus on the main {@link EditText} and shows the soft keyboard. */
public void requestFocusAndShowKeyboard() {
// Without a delay requesting focus on edit text fails when talkback is active.
editText.postDelayed(
() -> {
if (editText.requestFocus()) {
// Workaround for talkback issue when clear button is clicked
editText.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
}
ViewUtils.showKeyboard(editText, useWindowInsetsController);
},
TALKBACK_FOCUS_CHANGE_DELAY_MS);
}
/** Clears focus on the main {@link EditText} and hides the soft keyboard. */
public void clearFocusAndHideKeyboard() {
editText.post(
() -> {
editText.clearFocus();
if (searchBar != null) {
searchBar.requestFocus();
}
ViewUtils.hideKeyboard(editText, useWindowInsetsController);
});
}
boolean isAdjustNothingSoftInputMode() {
return softInputMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING;
}
/**
* Sets whether the {@link SearchView} is modal for accessibility, i.e., whether views that are
* not nested within the {@link SearchView} are important for accessibility.
*/
public void setModalForAccessibility(boolean isSearchViewModal) {
ViewGroup rootView = (ViewGroup) this.getRootView();
if (isSearchViewModal) {
childImportantForAccessibilityMap = new HashMap<>(rootView.getChildCount());
}
updateChildImportantForAccessibility(rootView, isSearchViewModal);
if (!isSearchViewModal) {
// When SearchView is not modal, reset the important for accessibility map.
childImportantForAccessibilityMap = null;
}
}
/**
* Sets the 'touchscreenBlocksFocus' attribute of the nested toolbar. The attribute defaults to
* 'true' for API level 26+. We need to set it to 'false' if keyboard navigation is needed for the
* search results.
*/
public void setToolbarTouchscreenBlocksFocus(boolean touchscreenBlocksFocus) {
if (Build.VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
toolbar.setTouchscreenBlocksFocus(touchscreenBlocksFocus);
}
}
@SuppressLint("InlinedApi") // View Compat will handle the differences.
private void updateChildImportantForAccessibility(ViewGroup parent, boolean isSearchViewModal) {
for (int i = 0; i < parent.getChildCount(); i++) {
final View child = parent.getChildAt(i);
if (child == this) {
continue;
}
if (child.findViewById(this.rootView.getId()) != null) {
// If this child node contains SearchView, look at this node's children instead.
updateChildImportantForAccessibility((ViewGroup) child, isSearchViewModal);
continue;
}
if (!isSearchViewModal) {
if (childImportantForAccessibilityMap != null
&& childImportantForAccessibilityMap.containsKey(child)) {
// Restores the original important for accessibility value of the child view.
child.setImportantForAccessibility(childImportantForAccessibilityMap.get(child));
}
} else {
// Saves the important for accessibility value of the child view.
childImportantForAccessibilityMap.put(child, child.getImportantForAccessibility());
child.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS);
}
}
}
/**
* Provides the resource identifier for the back arrow icon.