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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515
|
/*
* Copyright (C) 2007 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 android.widget;
import android.annotation.DrawableRes;
import android.annotation.IntDef;
import android.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.res.Resources.Theme;
import android.content.res.TypedArray;
import android.database.DataSetObserver;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.Editable;
import android.text.Selection;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.view.inputmethod.CompletionInfo;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.view.inspector.InspectableProperty;
import com.android.internal.R;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.ref.WeakReference;
/**
* <p>An editable text view that shows completion suggestions automatically
* while the user is typing. The list of suggestions is displayed in a drop
* down menu from which the user can choose an item to replace the content
* of the edit box with.</p>
*
* <p>The drop down can be dismissed at any time by pressing the back key or,
* if no item is selected in the drop down, by pressing the enter/dpad center
* key.</p>
*
* <p>The list of suggestions is obtained from a data adapter and appears
* only after a given number of characters defined by
* {@link #getThreshold() the threshold}.</p>
*
* <p>The following code snippet shows how to create a text view which suggests
* various countries names while the user is typing:</p>
*
* <pre class="prettyprint">
* public class CountriesActivity extends Activity {
* protected void onCreate(Bundle icicle) {
* super.onCreate(icicle);
* setContentView(R.layout.countries);
*
* ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
* android.R.layout.simple_dropdown_item_1line, COUNTRIES);
* AutoCompleteTextView textView = (AutoCompleteTextView)
* findViewById(R.id.countries_list);
* textView.setAdapter(adapter);
* }
*
* private static final String[] COUNTRIES = new String[] {
* "Belgium", "France", "Italy", "Germany", "Spain"
* };
* }
* </pre>
*
* <p>See the <a href="{@docRoot}guide/topics/ui/controls/text.html">Text Fields</a>
* guide.</p>
*
* @attr ref android.R.styleable#AutoCompleteTextView_completionHint
* @attr ref android.R.styleable#AutoCompleteTextView_completionThreshold
* @attr ref android.R.styleable#AutoCompleteTextView_completionHintView
* @attr ref android.R.styleable#AutoCompleteTextView_dropDownSelector
* @attr ref android.R.styleable#AutoCompleteTextView_dropDownAnchor
* @attr ref android.R.styleable#AutoCompleteTextView_dropDownWidth
* @attr ref android.R.styleable#AutoCompleteTextView_dropDownHeight
* @attr ref android.R.styleable#ListPopupWindow_dropDownVerticalOffset
* @attr ref android.R.styleable#ListPopupWindow_dropDownHorizontalOffset
*/
public class AutoCompleteTextView extends EditText implements Filter.FilterListener {
static final boolean DEBUG = false;
static final String TAG = "AutoCompleteTextView";
static final int EXPAND_MAX = 3;
/** Context used to inflate the popup window or dialog. */
private final Context mPopupContext;
@UnsupportedAppUsage
private final ListPopupWindow mPopup;
@UnsupportedAppUsage
private final PassThroughClickListener mPassThroughClickListener;
private CharSequence mHintText;
@UnsupportedAppUsage
private TextView mHintView;
private int mHintResource;
private ListAdapter mAdapter;
private Filter mFilter;
private int mThreshold;
private int mDropDownAnchorId;
private AdapterView.OnItemClickListener mItemClickListener;
private AdapterView.OnItemSelectedListener mItemSelectedListener;
private boolean mDropDownDismissedOnCompletion = true;
private int mLastKeyCode = KeyEvent.KEYCODE_UNKNOWN;
private MyWatcher mAutoCompleteTextWatcher;
private Validator mValidator = null;
// Set to true when text is set directly and no filtering shall be performed
private boolean mBlockCompletion;
// When set, an update in the underlying adapter will update the result list popup.
// Set to false when the list is hidden to prevent asynchronous updates to popup the list again.
private boolean mPopupCanBeUpdated = true;
@UnsupportedAppUsage
private PopupDataSetObserver mObserver;
/**
* Constructs a new auto-complete text view with the given context's theme.
*
* @param context The Context the view is running in, through which it can
* access the current theme, resources, etc.
*/
public AutoCompleteTextView(Context context) {
this(context, null);
}
/**
* Constructs a new auto-complete text view with the given context's theme
* and the supplied attribute set.
*
* @param context The Context the view is running in, through which it can
* access the current theme, resources, etc.
* @param attrs The attributes of the XML tag that is inflating the view.
*/
public AutoCompleteTextView(Context context, AttributeSet attrs) {
this(context, attrs, R.attr.autoCompleteTextViewStyle);
}
/**
* Constructs a new auto-complete text view with the given context's theme,
* the supplied attribute set, and default style attribute.
*
* @param context The Context the view is running in, through which it can
* access the current theme, resources, etc.
* @param attrs The attributes of the XML tag that is inflating the view.
* @param defStyleAttr An attribute in the current theme that contains a
* reference to a style resource that supplies default
* values for the view. Can be 0 to not look for
* defaults.
*/
public AutoCompleteTextView(Context context, AttributeSet attrs, int defStyleAttr) {
this(context, attrs, defStyleAttr, 0);
}
/**
* Constructs a new auto-complete text view with the given context's theme,
* the supplied attribute set, and default styles.
*
* @param context The Context the view is running in, through which it can
* access the current theme, resources, etc.
* @param attrs The attributes of the XML tag that is inflating the view.
* @param defStyleAttr An attribute in the current theme that contains a
* reference to a style resource that supplies default
* values for the view. Can be 0 to not look for
* defaults.
* @param defStyleRes A resource identifier of a style resource that
* supplies default values for the view, used only if
* defStyleAttr is 0 or can not be found in the theme.
* Can be 0 to not look for defaults.
*/
public AutoCompleteTextView(
Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
this(context, attrs, defStyleAttr, defStyleRes, null);
}
/**
* Constructs a new auto-complete text view with the given context, the
* supplied attribute set, default styles, and the theme against which the
* completion popup should be inflated.
*
* @param context The context against which the view is inflated, which
* provides access to the current theme, resources, etc.
* @param attrs The attributes of the XML tag that is inflating the view.
* @param defStyleAttr An attribute in the current theme that contains a
* reference to a style resource that supplies default
* values for the view. Can be 0 to not look for
* defaults.
* @param defStyleRes A resource identifier of a style resource that
* supplies default values for the view, used only if
* defStyleAttr is 0 or can not be found in the theme.
* Can be 0 to not look for defaults.
* @param popupTheme The theme against which the completion popup window
* should be inflated. May be {@code null} to use the
* view theme. If set, this will override any value
* specified by
* {@link android.R.styleable#AutoCompleteTextView_popupTheme}.
*/
public AutoCompleteTextView(Context context, AttributeSet attrs, int defStyleAttr,
int defStyleRes, Theme popupTheme) {
super(context, attrs, defStyleAttr, defStyleRes);
final TypedArray a = context.obtainStyledAttributes(
attrs, R.styleable.AutoCompleteTextView, defStyleAttr, defStyleRes);
saveAttributeDataForStyleable(context, R.styleable.AutoCompleteTextView,
attrs, a, defStyleAttr, defStyleRes);
if (popupTheme != null) {
mPopupContext = new ContextThemeWrapper(context, popupTheme);
} else {
final int popupThemeResId = a.getResourceId(
R.styleable.AutoCompleteTextView_popupTheme, 0);
if (popupThemeResId != 0) {
mPopupContext = new ContextThemeWrapper(context, popupThemeResId);
} else {
mPopupContext = context;
}
}
// Load attributes used within the popup against the popup context.
final TypedArray pa;
if (mPopupContext != context) {
pa = mPopupContext.obtainStyledAttributes(
attrs, R.styleable.AutoCompleteTextView, defStyleAttr, defStyleRes);
saveAttributeDataForStyleable(context, R.styleable.AutoCompleteTextView,
attrs, a, defStyleAttr, defStyleRes);
} else {
pa = a;
}
final Drawable popupListSelector = pa.getDrawable(
R.styleable.AutoCompleteTextView_dropDownSelector);
final int popupWidth = pa.getLayoutDimension(
R.styleable.AutoCompleteTextView_dropDownWidth, LayoutParams.WRAP_CONTENT);
final int popupHeight = pa.getLayoutDimension(
R.styleable.AutoCompleteTextView_dropDownHeight, LayoutParams.WRAP_CONTENT);
final int popupHintLayoutResId = pa.getResourceId(
R.styleable.AutoCompleteTextView_completionHintView, R.layout.simple_dropdown_hint);
final CharSequence popupHintText = pa.getText(
R.styleable.AutoCompleteTextView_completionHint);
if (pa != a) {
pa.recycle();
}
mPopup = new ListPopupWindow(mPopupContext, attrs, defStyleAttr, defStyleRes);
mPopup.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
mPopup.setPromptPosition(ListPopupWindow.POSITION_PROMPT_BELOW);
mPopup.setListSelector(popupListSelector);
mPopup.setOnItemClickListener(new DropDownItemClickListener());
// For dropdown width, the developer can specify a specific width, or
// MATCH_PARENT (for full screen width), or WRAP_CONTENT (to match the
// width of the anchored view).
mPopup.setWidth(popupWidth);
mPopup.setHeight(popupHeight);
// Completion hint must be set after specifying hint layout.
mHintResource = popupHintLayoutResId;
setCompletionHint(popupHintText);
// Get the anchor's id now, but the view won't be ready, so wait to
// actually get the view and store it in mDropDownAnchorView lazily in
// getDropDownAnchorView later. Defaults to NO_ID, in which case the
// getDropDownAnchorView method will simply return this TextView, as a
// default anchoring point.
mDropDownAnchorId = a.getResourceId(
R.styleable.AutoCompleteTextView_dropDownAnchor, View.NO_ID);
mThreshold = a.getInt(R.styleable.AutoCompleteTextView_completionThreshold, 2);
a.recycle();
// Always turn on the auto complete input type flag, since it
// makes no sense to use this widget without it.
int inputType = getInputType();
if ((inputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) {
inputType |= EditorInfo.TYPE_TEXT_FLAG_AUTO_COMPLETE;
setRawInputType(inputType);
}
setFocusable(true);
mAutoCompleteTextWatcher = new MyWatcher();
addTextChangedListener(mAutoCompleteTextWatcher);
mPassThroughClickListener = new PassThroughClickListener();
super.setOnClickListener(mPassThroughClickListener);
}
@Override
public void setOnClickListener(OnClickListener listener) {
mPassThroughClickListener.mWrapped = listener;
}
/**
* Private hook into the on click event, dispatched from {@link PassThroughClickListener}
*/
private void onClickImpl() {
// If the dropdown is showing, bring the keyboard to the front
// when the user touches the text field.
if (isPopupShowing()) {
ensureImeVisible(true);
}
}
/**
* <p>Sets the optional hint text that is displayed at the bottom of the
* the matching list. This can be used as a cue to the user on how to
* best use the list, or to provide extra information.</p>
*
* @param hint the text to be displayed to the user
*
* @see #getCompletionHint()
*
* @attr ref android.R.styleable#AutoCompleteTextView_completionHint
*/
public void setCompletionHint(CharSequence hint) {
mHintText = hint;
if (hint != null) {
if (mHintView == null) {
final TextView hintView = (TextView) LayoutInflater.from(mPopupContext).inflate(
mHintResource, null).findViewById(R.id.text1);
hintView.setText(mHintText);
mHintView = hintView;
mPopup.setPromptView(hintView);
} else {
mHintView.setText(hint);
}
} else {
mPopup.setPromptView(null);
mHintView = null;
}
}
/**
* Gets the optional hint text displayed at the bottom of the the matching list.
*
* @return The hint text, if any
*
* @see #setCompletionHint(CharSequence)
*
* @attr ref android.R.styleable#AutoCompleteTextView_completionHint
*/
@InspectableProperty
public CharSequence getCompletionHint() {
return mHintText;
}
/**
* Returns the current width for the auto-complete drop down list.
*
* This can be a fixed width, or {@link android.view.ViewGroup.LayoutParams#MATCH_PARENT}
* to fill the screen, or {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT}
* to fit the width of its anchor view.
*
* @return the width for the drop down list
*
* @attr ref android.R.styleable#AutoCompleteTextView_dropDownWidth
*/
@InspectableProperty
public int getDropDownWidth() {
return mPopup.getWidth();
}
/**
* Sets the current width for the auto-complete drop down list.
*
* This can be a fixed width, or {@link android.view.ViewGroup.LayoutParams#MATCH_PARENT}
* to fill the screen, or {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT}
* to fit the width of its anchor view.
*
* @param width the width to use
*
* @attr ref android.R.styleable#AutoCompleteTextView_dropDownWidth
*/
public void setDropDownWidth(int width) {
mPopup.setWidth(width);
}
/**
* <p>Returns the current height for the auto-complete drop down list.
*
* This can be a fixed width, or {@link android.view.ViewGroup.LayoutParams#MATCH_PARENT}
* to fill the screen, or {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT}
* to fit the width of its anchor view.
*
* @return the height for the drop down list
*
* @attr ref android.R.styleable#AutoCompleteTextView_dropDownHeight
*/
@InspectableProperty
public int getDropDownHeight() {
return mPopup.getHeight();
}
/**
* Sets the current height for the auto-complete drop down list.
*
* This can be a fixed width, or {@link android.view.ViewGroup.LayoutParams#MATCH_PARENT}
* to fill the screen, or {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT}
* to fit the width of its anchor view.
*
* @param height the height to use
*
* @attr ref android.R.styleable#AutoCompleteTextView_dropDownHeight
*/
public void setDropDownHeight(int height) {
mPopup.setHeight(height);
}
/**
* <p>Returns the id for the view that the auto-complete drop down list is anchored to.</p>
*
* @return the view's id, or {@link View#NO_ID} if none specified
*
* @attr ref android.R.styleable#AutoCompleteTextView_dropDownAnchor
*/
public int getDropDownAnchor() {
return mDropDownAnchorId;
}
/**
* <p>Sets the view to which the auto-complete drop down list should anchor. The view
* corresponding to this id will not be loaded until the next time it is needed to avoid
* loading a view which is not yet instantiated.</p>
*
* @param id the id to anchor the drop down list view to
*
* @attr ref android.R.styleable#AutoCompleteTextView_dropDownAnchor
*/
public void setDropDownAnchor(int id) {
mDropDownAnchorId = id;
mPopup.setAnchorView(null);
}
/**
* <p>Gets the background of the auto-complete drop-down list.</p>
*
* @return the background drawable
*
* @attr ref android.R.styleable#PopupWindow_popupBackground
*/
@InspectableProperty(name = "popupBackground")
public Drawable getDropDownBackground() {
return mPopup.getBackground();
}
/**
* <p>Sets the background of the auto-complete drop-down list.</p>
*
* @param d the drawable to set as the background
*
* @attr ref android.R.styleable#PopupWindow_popupBackground
*/
public void setDropDownBackgroundDrawable(Drawable d) {
mPopup.setBackgroundDrawable(d);
}
/**
* <p>Sets the background of the auto-complete drop-down list.</p>
*
* @param id the id of the drawable to set as the background
*
* @attr ref android.R.styleable#PopupWindow_popupBackground
*/
public void setDropDownBackgroundResource(@DrawableRes int id) {
mPopup.setBackgroundDrawable(getContext().getDrawable(id));
}
/**
* <p>Sets the vertical offset used for the auto-complete drop-down list.</p>
*
* @param offset the vertical offset
*
* @attr ref android.R.styleable#ListPopupWindow_dropDownVerticalOffset
*/
public void setDropDownVerticalOffset(int offset) {
mPopup.setVerticalOffset(offset);
}
/**
* <p>Gets the vertical offset used for the auto-complete drop-down list.</p>
*
* @return the vertical offset
*
* @attr ref android.R.styleable#ListPopupWindow_dropDownVerticalOffset
*/
@InspectableProperty
public int getDropDownVerticalOffset() {
return mPopup.getVerticalOffset();
}
/**
* <p>Sets the horizontal offset used for the auto-complete drop-down list.</p>
*
* @param offset the horizontal offset
*
* @attr ref android.R.styleable#ListPopupWindow_dropDownHorizontalOffset
*/
public void setDropDownHorizontalOffset(int offset) {
mPopup.setHorizontalOffset(offset);
}
/**
* <p>Gets the horizontal offset used for the auto-complete drop-down list.</p>
*
* @return the horizontal offset
*
* @attr ref android.R.styleable#ListPopupWindow_dropDownHorizontalOffset
*/
@InspectableProperty
public int getDropDownHorizontalOffset() {
return mPopup.getHorizontalOffset();
}
/**
* <p>Sets the animation style of the auto-complete drop-down list.</p>
*
* <p>If the drop-down is showing, calling this method will take effect only
* the next time the drop-down is shown.</p>
*
* @param animationStyle animation style to use when the drop-down appears
* and disappears. Set to -1 for the default animation, 0 for no
* animation, or a resource identifier for an explicit animation.
*
* @hide Pending API council approval
*/
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
public void setDropDownAnimationStyle(int animationStyle) {
mPopup.setAnimationStyle(animationStyle);
}
/**
* <p>Returns the animation style that is used when the drop-down list appears and disappears
* </p>
*
* @return the animation style that is used when the drop-down list appears and disappears
*
* @hide Pending API council approval
*/
public int getDropDownAnimationStyle() {
return mPopup.getAnimationStyle();
}
/**
* @return Whether the drop-down is visible as long as there is {@link #enoughToFilter()}
*
* @hide Pending API council approval
*/
public boolean isDropDownAlwaysVisible() {
return mPopup.isDropDownAlwaysVisible();
}
/**
* Sets whether the drop-down should remain visible as long as there is there is
* {@link #enoughToFilter()}. This is useful if an unknown number of results are expected
* to show up in the adapter sometime in the future.
*
* The drop-down will occupy the entire screen below {@link #getDropDownAnchor} regardless
* of the size or content of the list. {@link #getDropDownBackground()} will fill any space
* that is not used by the list.
*
* @param dropDownAlwaysVisible Whether to keep the drop-down visible.
*
* @hide Pending API council approval
*/
@UnsupportedAppUsage
public void setDropDownAlwaysVisible(boolean dropDownAlwaysVisible) {
mPopup.setDropDownAlwaysVisible(dropDownAlwaysVisible);
}
/**
* Checks whether the drop-down is dismissed when a suggestion is clicked.
*
* @hide Pending API council approval
*/
public boolean isDropDownDismissedOnCompletion() {
return mDropDownDismissedOnCompletion;
}
/**
* Sets whether the drop-down is dismissed when a suggestion is clicked. This is
* true by default.
*
* @param dropDownDismissedOnCompletion Whether to dismiss the drop-down.
*
* @hide Pending API council approval
*/
@UnsupportedAppUsage
public void setDropDownDismissedOnCompletion(boolean dropDownDismissedOnCompletion) {
mDropDownDismissedOnCompletion = dropDownDismissedOnCompletion;
}
/**
* <p>Returns the number of characters the user must type before the drop
* down list is shown.</p>
*
* @return the minimum number of characters to type to show the drop down
*
* @see #setThreshold(int)
*
* @attr ref android.R.styleable#AutoCompleteTextView_completionThreshold
*/
@InspectableProperty(name = "completionThreshold")
public int getThreshold() {
return mThreshold;
}
/**
* <p>Specifies the minimum number of characters the user has to type in the
* edit box before the drop down list is shown.</p>
*
* <p>When <code>threshold</code> is less than or equals 0, a threshold of
* 1 is applied.</p>
*
* @param threshold the number of characters to type before the drop down
* is shown
*
* @see #getThreshold()
*
* @attr ref android.R.styleable#AutoCompleteTextView_completionThreshold
*/
public void setThreshold(int threshold) {
if (threshold <= 0) {
threshold = 1;
}
mThreshold = threshold;
}
/**
* <p>Sets the listener that will be notified when the user clicks an item
* in the drop down list.</p>
*
* @param l the item click listener
*/
public void setOnItemClickListener(AdapterView.OnItemClickListener l) {
mItemClickListener = l;
}
/**
* <p>Sets the listener that will be notified when the user selects an item
* in the drop down list.</p>
*
* @param l the item selected listener
*/
public void setOnItemSelectedListener(AdapterView.OnItemSelectedListener l) {
mItemSelectedListener = l;
}
/**
* <p>Returns the listener that is notified whenever the user clicks an item
* in the drop down list.</p>
*
* @return the item click listener
*
* @deprecated Use {@link #getOnItemClickListener()} intead
*/
@Deprecated
public AdapterView.OnItemClickListener getItemClickListener() {
return mItemClickListener;
}
/**
* <p>Returns the listener that is notified whenever the user selects an
* item in the drop down list.</p>
*
* @return the item selected listener
*
* @deprecated Use {@link #getOnItemSelectedListener()} intead
*/
@Deprecated
public AdapterView.OnItemSelectedListener getItemSelectedListener() {
return mItemSelectedListener;
}
/**
* <p>Returns the listener that is notified whenever the user clicks an item
* in the drop down list.</p>
*
* @return the item click listener
*/
public AdapterView.OnItemClickListener getOnItemClickListener() {
return mItemClickListener;
}
/**
* <p>Returns the listener that is notified whenever the user selects an
* item in the drop down list.</p>
*
* @return the item selected listener
*/
public AdapterView.OnItemSelectedListener getOnItemSelectedListener() {
return mItemSelectedListener;
}
/**
* Set a listener that will be invoked whenever the AutoCompleteTextView's
* list of completions is dismissed.
* @param dismissListener Listener to invoke when completions are dismissed
*/
public void setOnDismissListener(final OnDismissListener dismissListener) {
PopupWindow.OnDismissListener wrappedListener = null;
if (dismissListener != null) {
wrappedListener = new PopupWindow.OnDismissListener() {
@Override public void onDismiss() {
dismissListener.onDismiss();
}
};
}
mPopup.setOnDismissListener(wrappedListener);
}
/**
* <p>Returns a filterable list adapter used for auto completion.</p>
*
* @return a data adapter used for auto completion
*/
public ListAdapter getAdapter() {
return mAdapter;
}
/**
* <p>Changes the list of data used for auto completion. The provided list
* must be a filterable list adapter.</p>
*
* <p>The caller is still responsible for managing any resources used by the adapter.
* Notably, when the AutoCompleteTextView is closed or released, the adapter is not notified.
* A common case is the use of {@link android.widget.CursorAdapter}, which
* contains a {@link android.database.Cursor} that must be closed. This can be done
* automatically (see
* {@link android.app.Activity#startManagingCursor(android.database.Cursor)
* startManagingCursor()}),
* or by manually closing the cursor when the AutoCompleteTextView is dismissed.</p>
*
* @param adapter the adapter holding the auto completion data
*
* @see #getAdapter()
* @see android.widget.Filterable
* @see android.widget.ListAdapter
*/
public <T extends ListAdapter & Filterable> void setAdapter(T adapter) {
if (mObserver == null) {
mObserver = new PopupDataSetObserver(this);
} else if (mAdapter != null) {
mAdapter.unregisterDataSetObserver(mObserver);
}
mAdapter = adapter;
if (mAdapter != null) {
//noinspection unchecked
mFilter = ((Filterable) mAdapter).getFilter();
adapter.registerDataSetObserver(mObserver);
} else {
mFilter = null;
}
mPopup.setAdapter(mAdapter);
}
@Override
public boolean onKeyPreIme(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && isPopupShowing()
&& !mPopup.isDropDownAlwaysVisible()) {
// special case for the back key, we do not even try to send it
// to the drop down list but instead, consume it immediately
if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {
KeyEvent.DispatcherState state = getKeyDispatcherState();
if (state != null) {
state.startTracking(event, this);
}
return true;
} else if (event.getAction() == KeyEvent.ACTION_UP) {
KeyEvent.DispatcherState state = getKeyDispatcherState();
if (state != null) {
state.handleUpEvent(event);
}
if (event.isTracking() && !event.isCanceled()) {
dismissDropDown();
return true;
}
}
}
return super.onKeyPreIme(keyCode, event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
boolean consumed = mPopup.onKeyUp(keyCode, event);
if (consumed) {
switch (keyCode) {
// if the list accepts the key events and the key event
// was a click, the text view gets the selected item
// from the drop down as its content
case KeyEvent.KEYCODE_ENTER:
case KeyEvent.KEYCODE_DPAD_CENTER:
case KeyEvent.KEYCODE_TAB:
if (event.hasNoModifiers()) {
performCompletion();
}
return true;
}
}
if (isPopupShowing() && keyCode == KeyEvent.KEYCODE_TAB && event.hasNoModifiers()) {
performCompletion();
return true;
}
return super.onKeyUp(keyCode, event);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (mPopup.onKeyDown(keyCode, event)) {
return true;
}
if (!isPopupShowing()) {
switch(keyCode) {
case KeyEvent.KEYCODE_DPAD_DOWN:
if (event.hasNoModifiers()) {
performValidation();
}
}
}
if (isPopupShowing() && keyCode == KeyEvent.KEYCODE_TAB && event.hasNoModifiers()) {
return true;
}
mLastKeyCode = keyCode;
boolean handled = super.onKeyDown(keyCode, event);
mLastKeyCode = KeyEvent.KEYCODE_UNKNOWN;
if (handled && isPopupShowing()) {
clearListSelection();
}
return handled;
}
/**
* Returns <code>true</code> if the amount of text in the field meets
* or exceeds the {@link #getThreshold} requirement. You can override
* this to impose a different standard for when filtering will be
* triggered.
*/
public boolean enoughToFilter() {
if (DEBUG) Log.v(TAG, "Enough to filter: len=" + getText().length()
+ " threshold=" + mThreshold);
return getText().length() >= mThreshold;
}
/** This is used to watch for edits to the text view. */
private class MyWatcher implements TextWatcher {
private boolean mOpenBefore;
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
if (mBlockCompletion) return;
// when text is changed, inserted or deleted, we attempt to show
// the drop down
mOpenBefore = isPopupShowing();
if (DEBUG) Log.v(TAG, "before text changed: open=" + mOpenBefore);
}
public void afterTextChanged(Editable s) {
if (mBlockCompletion) return;
// if the list was open before the keystroke, but closed afterwards,
// then something in the keystroke processing (an input filter perhaps)
// called performCompletion() and we shouldn't do any more processing.
if (DEBUG) {
Log.v(TAG, "after text changed: openBefore=" + mOpenBefore
+ " open=" + isPopupShowing());
}
if (mOpenBefore && !isPopupShowing()) return;
refreshAutoCompleteResults();
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
}
/**
* This function is deprecated. Please use {@link #refreshAutoCompleteResults} instead.
* Note: Remove {@link #mAutoCompleteTextWatcher} after removing this function.
*/
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
void doBeforeTextChanged() {
mAutoCompleteTextWatcher.beforeTextChanged(null, 0, 0, 0);
}
/**
* This function is deprecated. Please use {@link #refreshAutoCompleteResults} instead.
* Note: Remove {@link #mAutoCompleteTextWatcher} after removing this function.
*/
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
void doAfterTextChanged() {
mAutoCompleteTextWatcher.afterTextChanged(null);
}
/**
* Refreshes the auto complete results. You usually shouldn't have to manually refresh the
* AutoCompleteResults as this is done automatically whenever the text changes. However if the
* results are not available and have to be fetched, you can call this function after fetching
* the results.
*/
public final void refreshAutoCompleteResults() {
// the drop down is shown only when a minimum number of characters
// was typed in the text view
if (enoughToFilter()) {
if (mFilter != null) {
mPopupCanBeUpdated = true;
performFiltering(getText(), mLastKeyCode);
}
} else {
// drop down is automatically dismissed when enough characters
// are deleted from the text view
if (!mPopup.isDropDownAlwaysVisible()) {
dismissDropDown();
}
if (mFilter != null) {
mFilter.filter(null);
}
}
}
/**
* <p>Indicates whether the popup menu is showing.</p>
*
* @return true if the popup menu is showing, false otherwise
*/
public boolean isPopupShowing() {
return mPopup.isShowing();
}
/**
* <p>Converts the selected item from the drop down list into a sequence
* of character that can be used in the edit box.</p>
*
* @param selectedItem the item selected by the user for completion
*
* @return a sequence of characters representing the selected suggestion
*/
protected CharSequence convertSelectionToString(Object selectedItem) {
return mFilter.convertResultToString(selectedItem);
}
/**
* <p>Clear the list selection. This may only be temporary, as user input will often bring
* it back.
*/
public void clearListSelection() {
mPopup.clearListSelection();
}
/**
* Set the position of the dropdown view selection.
*
* @param position The position to move the selector to.
*/
public void setListSelection(int position) {
mPopup.setSelection(position);
}
/**
* Get the position of the dropdown view selection, if there is one. Returns
* {@link ListView#INVALID_POSITION ListView.INVALID_POSITION} if there is no dropdown or if
* there is no selection.
*
* @return the position of the current selection, if there is one, or
* {@link ListView#INVALID_POSITION ListView.INVALID_POSITION} if not.
*
* @see ListView#getSelectedItemPosition()
*/
public int getListSelection() {
return mPopup.getSelectedItemPosition();
}
/**
* <p>Starts filtering the content of the drop down list. The filtering
* pattern is the content of the edit box. Subclasses should override this
* method to filter with a different pattern, for instance a substring of
* <code>text</code>.</p>
*
* @param text the filtering pattern
* @param keyCode the last character inserted in the edit box; beware that
* this will be null when text is being added through a soft input method.
*/
@SuppressWarnings({ "UnusedDeclaration" })
protected void performFiltering(CharSequence text, int keyCode) {
mFilter.filter(text, this);
}
/**
* <p>Performs the text completion by converting the selected item from
* the drop down list into a string, replacing the text box's content with
* this string and finally dismissing the drop down menu.</p>
*/
public void performCompletion() {
performCompletion(null, -1, -1);
}
@Override
public void onCommitCompletion(CompletionInfo completion) {
if (isPopupShowing()) {
mPopup.performItemClick(completion.getPosition());
}
}
private void performCompletion(View selectedView, int position, long id) {
if (isPopupShowing()) {
Object selectedItem;
if (position < 0) {
selectedItem = mPopup.getSelectedItem();
} else {
selectedItem = mAdapter.getItem(position);
}
if (selectedItem == null) {
Log.w(TAG, "performCompletion: no selected item");
return;
}
mBlockCompletion = true;
replaceText(convertSelectionToString(selectedItem));
mBlockCompletion = false;
if (mItemClickListener != null) {
final ListPopupWindow list = mPopup;
if (selectedView == null || position < 0) {
selectedView = list.getSelectedView();
position = list.getSelectedItemPosition();
id = list.getSelectedItemId();
}
mItemClickListener.onItemClick(list.getListView(), selectedView, position, id);
}
}
if (mDropDownDismissedOnCompletion && !mPopup.isDropDownAlwaysVisible()) {
dismissDropDown();
}
}
/**
* Identifies whether the view is currently performing a text completion, so subclasses
* can decide whether to respond to text changed events.
*/
public boolean isPerformingCompletion() {
return mBlockCompletion;
}
/**
* Like {@link #setText(CharSequence)}, except that it can disable filtering.
*
* @param filter If <code>false</code>, no filtering will be performed
* as a result of this call.
*/
public void setText(CharSequence text, boolean filter) {
if (filter) {
setText(text);
} else {
mBlockCompletion = true;
setText(text);
mBlockCompletion = false;
}
}
/**
* <p>Performs the text completion by replacing the current text by the
* selected item. Subclasses should override this method to avoid replacing
* the whole content of the edit box.</p>
*
* @param text the selected suggestion in the drop down list
*/
protected void replaceText(CharSequence text) {
clearComposingText();
setText(text);
// make sure we keep the caret at the end of the text view
Editable spannable = getText();
Selection.setSelection(spannable, spannable.length());
}
/** {@inheritDoc} */
public void onFilterComplete(int count) {
updateDropDownForFilter(count);
}
private void updateDropDownForFilter(int count) {
// Not attached to window, don't update drop-down
if (getWindowVisibility() == View.GONE) return;
/*
* This checks enoughToFilter() again because filtering requests
* are asynchronous, so the result may come back after enough text
* has since been deleted to make it no longer appropriate
* to filter.
*/
final boolean dropDownAlwaysVisible = mPopup.isDropDownAlwaysVisible();
final boolean enoughToFilter = enoughToFilter();
if ((count > 0 || dropDownAlwaysVisible) && enoughToFilter) {
if (hasFocus() && hasWindowFocus() && mPopupCanBeUpdated) {
showDropDown();
}
} else if (!dropDownAlwaysVisible && isPopupShowing()) {
dismissDropDown();
// When the filter text is changed, the first update from the adapter may show an empty
// count (when the query is being performed on the network). Future updates when some
// content has been retrieved should still be able to update the list.
mPopupCanBeUpdated = true;
}
}
@Override
public void onWindowFocusChanged(boolean hasWindowFocus) {
super.onWindowFocusChanged(hasWindowFocus);
if (!hasWindowFocus && !mPopup.isDropDownAlwaysVisible()) {
dismissDropDown();
}
}
@Override
protected void onDisplayHint(int hint) {
super.onDisplayHint(hint);
switch (hint) {
case INVISIBLE:
if (!mPopup.isDropDownAlwaysVisible()) {
dismissDropDown();
}
break;
}
}
@Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
super.onFocusChanged(focused, direction, previouslyFocusedRect);
if (isTemporarilyDetached()) {
// If we are temporarily in the detach state, then do nothing.
return;
}
// Perform validation if the view is losing focus.
if (!focused) {
performValidation();
}
if (!focused && !mPopup.isDropDownAlwaysVisible()) {
dismissDropDown();
}
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
}
@Override
protected void onDetachedFromWindow() {
dismissDropDown();
super.onDetachedFromWindow();
}
/**
* <p>Closes the drop down if present on screen.</p>
*/
public void dismissDropDown() {
InputMethodManager imm = getContext().getSystemService(InputMethodManager.class);
if (imm != null) {
imm.displayCompletions(this, null);
}
mPopup.dismiss();
mPopupCanBeUpdated = false;
}
@Override
protected boolean setFrame(final int l, int t, final int r, int b) {
boolean result = super.setFrame(l, t, r, b);
if (isPopupShowing()) {
showDropDown();
}
return result;
}
/**
* Issues a runnable to show the dropdown as soon as possible.
*
* @hide internal used only by SearchDialog
*/
@UnsupportedAppUsage
public void showDropDownAfterLayout() {
mPopup.postShow();
}
/**
* Ensures that the drop down is not obscuring the IME.
* @param visible whether the ime should be in front. If false, the ime is pushed to
* the background.
*
* This method is deprecated. Please use the following methods instead.
* Use {@link #setInputMethodMode} to ensure that the drop down is not obscuring the IME.
* Use {@link #showDropDown()} to show the drop down immediately
* A combination of {@link #isDropDownAlwaysVisible()} and {@link #enoughToFilter()} to decide
* whether to manually trigger {@link #showDropDown()} or not.
*
* @hide internal used only here and SearchDialog
*/
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 123768913)
public void ensureImeVisible(boolean visible) {
mPopup.setInputMethodMode(visible
? ListPopupWindow.INPUT_METHOD_NEEDED : ListPopupWindow.INPUT_METHOD_NOT_NEEDED);
if (mPopup.isDropDownAlwaysVisible() || (mFilter != null && enoughToFilter())) {
showDropDown();
}
}
/**
* This method is deprecated. Please use {@link #getInputMethodMode()} instead.
*
* @hide This API is not being used and can be removed.
*/
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
public boolean isInputMethodNotNeeded() {
return mPopup.getInputMethodMode() == ListPopupWindow.INPUT_METHOD_NOT_NEEDED;
}
/**
* The valid input method modes for the {@link AutoCompleteTextView}:
*
* {@hide}
*/
@IntDef({ListPopupWindow.INPUT_METHOD_FROM_FOCUSABLE,
ListPopupWindow.INPUT_METHOD_NEEDED,
ListPopupWindow.INPUT_METHOD_NOT_NEEDED})
@Retention(RetentionPolicy.SOURCE)
public @interface InputMethodMode {}
/**
* Returns the input method mode used by the auto complete dropdown.
*/
public @InputMethodMode int getInputMethodMode() {
return mPopup.getInputMethodMode();
}
/**
* Use this method to specify when the IME should be displayed. This function can be used to
* prevent the dropdown from obscuring the IME.
*
* @param mode speficies the input method mode. use one of the following values:
*
* {@link ListPopupWindow#INPUT_METHOD_FROM_FOCUSABLE} IME Displayed if the auto-complete box is
* focusable.
* {@link ListPopupWindow#INPUT_METHOD_NEEDED} Always display the IME.
* {@link ListPopupWindow#INPUT_METHOD_NOT_NEEDED}. The auto-complete suggestions are always
* displayed, even if the suggestions cover/hide the input method.
*/
public void setInputMethodMode(@InputMethodMode int mode) {
mPopup.setInputMethodMode(mode);
}
/**
* <p>Displays the drop down on screen.</p>
*/
public void showDropDown() {
buildImeCompletions();
if (mPopup.getAnchorView() == null) {
if (mDropDownAnchorId != View.NO_ID) {
mPopup.setAnchorView(getRootView().findViewById(mDropDownAnchorId));
} else {
mPopup.setAnchorView(this);
}
}
if (!isPopupShowing()) {
// Make sure the list does not obscure the IME when shown for the first time.
mPopup.setInputMethodMode(ListPopupWindow.INPUT_METHOD_NEEDED);
mPopup.setListItemExpandMax(EXPAND_MAX);
}
mPopup.show();
mPopup.getListView().setOverScrollMode(View.OVER_SCROLL_ALWAYS);
}
/**
* Forces outside touches to be ignored. Normally if {@link #isDropDownAlwaysVisible()} is
* false, we allow outside touch to dismiss the dropdown. If this is set to true, then we
* ignore outside touch even when the drop down is not set to always visible.
*
* @hide used only by SearchDialog
*/
@UnsupportedAppUsage
public void setForceIgnoreOutsideTouch(boolean forceIgnoreOutsideTouch) {
mPopup.setForceIgnoreOutsideTouch(forceIgnoreOutsideTouch);
}
private void buildImeCompletions() {
final ListAdapter adapter = mAdapter;
if (adapter != null) {
InputMethodManager imm = getContext().getSystemService(InputMethodManager.class);
if (imm != null) {
final int count = Math.min(adapter.getCount(), 20);
CompletionInfo[] completions = new CompletionInfo[count];
int realCount = 0;
for (int i = 0; i < count; i++) {
if (adapter.isEnabled(i)) {
Object item = adapter.getItem(i);
long id = adapter.getItemId(i);
completions[realCount] = new CompletionInfo(id, realCount,
convertSelectionToString(item));
realCount++;
}
}
if (realCount != count) {
CompletionInfo[] tmp = new CompletionInfo[realCount];
System.arraycopy(completions, 0, tmp, 0, realCount);
completions = tmp;
}
imm.displayCompletions(this, completions);
}
}
}
/**
* Sets the validator used to perform text validation.
*
* @param validator The validator used to validate the text entered in this widget.
*
* @see #getValidator()
* @see #performValidation()
*/
public void setValidator(Validator validator) {
mValidator = validator;
}
/**
* Returns the Validator set with {@link #setValidator},
* or <code>null</code> if it was not set.
*
* @see #setValidator(android.widget.AutoCompleteTextView.Validator)
* @see #performValidation()
*/
public Validator getValidator() {
return mValidator;
}
/**
* If a validator was set on this view and the current string is not valid,
* ask the validator to fix it.
*
* @see #getValidator()
* @see #setValidator(android.widget.AutoCompleteTextView.Validator)
*/
public void performValidation() {
if (mValidator == null) return;
CharSequence text = getText();
if (!TextUtils.isEmpty(text) && !mValidator.isValid(text)) {
setText(mValidator.fixText(text));
}
}
/**
* Returns the Filter obtained from {@link Filterable#getFilter},
* or <code>null</code> if {@link #setAdapter} was not called with
* a Filterable.
*/
protected Filter getFilter() {
return mFilter;
}
private class DropDownItemClickListener implements AdapterView.OnItemClickListener {
public void onItemClick(AdapterView parent, View v, int position, long id) {
performCompletion(v, position, id);
}
}
/**
* This interface is used to make sure that the text entered in this TextView complies to
* a certain format. Since there is no foolproof way to prevent the user from leaving
* this View with an incorrect value in it, all we can do is try to fix it ourselves
* when this happens.
*/
public interface Validator {
/**
* Validates the specified text.
*
* @return true If the text currently in the text editor is valid.
*
* @see #fixText(CharSequence)
*/
boolean isValid(CharSequence text);
/**
* Corrects the specified text to make it valid.
*
* @param invalidText A string that doesn't pass validation: isValid(invalidText)
* returns false
*
* @return A string based on invalidText such as invoking isValid() on it returns true.
*
* @see #isValid(CharSequence)
*/
CharSequence fixText(CharSequence invalidText);
}
/**
* Listener to respond to the AutoCompleteTextView's completion list being dismissed.
* @see AutoCompleteTextView#setOnDismissListener(OnDismissListener)
*/
public interface OnDismissListener {
/**
* This method will be invoked whenever the AutoCompleteTextView's list
* of completion options has been dismissed and is no longer available
* for user interaction.
*/
void onDismiss();
}
/**
* Allows us a private hook into the on click event without preventing users from setting
* their own click listener.
*/
private class PassThroughClickListener implements OnClickListener {
private View.OnClickListener mWrapped;
/** {@inheritDoc} */
public void onClick(View v) {
onClickImpl();
if (mWrapped != null) mWrapped.onClick(v);
}
}
/**
* Static inner listener that keeps a WeakReference to the actual AutoCompleteTextView.
* <p>
* This way, if adapter has a longer life span than the View, we won't leak the View, instead
* we will just leak a small Observer with 1 field.
*/
private static class PopupDataSetObserver extends DataSetObserver {
private final WeakReference<AutoCompleteTextView> mViewReference;
private PopupDataSetObserver(AutoCompleteTextView view) {
mViewReference = new WeakReference<AutoCompleteTextView>(view);
}
@Override
public void onChanged() {
final AutoCompleteTextView textView = mViewReference.get();
if (textView != null && textView.mAdapter != null) {
// If the popup is not showing already, showing it will cause
// the list of data set observers attached to the adapter to
// change. We can't do it from here, because we are in the middle
// of iterating through the list of observers.
textView.post(updateRunnable);
}
}
private final Runnable updateRunnable = new Runnable() {
@Override
public void run() {
final AutoCompleteTextView textView = mViewReference.get();
if (textView == null) {
return;
}
final ListAdapter adapter = textView.mAdapter;
if (adapter == null) {
return;
}
textView.updateDropDownForFilter(adapter.getCount());
}
};
}
}
|