下面列出了怎么用android.widget.AutoCompleteTextView的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void onAutofillEvent(@NonNull View view, int event) {
if (view instanceof AutoCompleteTextView) {
switch (event) {
case AutofillManager.AutofillCallback.EVENT_INPUT_UNAVAILABLE:
// no break on purpose
case AutofillManager.AutofillCallback.EVENT_INPUT_HIDDEN:
if (!mAutofillReceived) {
((AutoCompleteTextView) view).showDropDown();
}
break;
case AutofillManager.AutofillCallback.EVENT_INPUT_SHOWN:
mAutofillReceived = true;
((AutoCompleteTextView) view).setAdapter(null);
break;
default:
Log.d(TAG, "Unexpected callback: " + event);
}
}
}
/**
* This method is used to get values in displayed view and perform actions accordingly
*/
private void defineView(){
mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
registerCheckBox = (CheckBox)findViewById(R.id.isRegister);
mPasswordView = (EditText) findViewById(R.id.password);
Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
mEmailSignInButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
attemptLogin();
/* Intent myIntent = new Intent(view.getContext(), HomeActivity.class);
startActivityForResult(myIntent, 0);
finish();*/
}
});
mLoginFormView = findViewById(R.id.login_form);
mProgressView = findViewById(R.id.login_progress);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ActionBar actionBar = getActionBar();
actionBar.setTitle(R.string.app_name);
actionBar.setSubtitle(null);
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setHomeButtonEnabled(false);
fragment = (MainFragment) getSupportFragmentManager().findFragmentById(R.id.main_fragment);
search = (AutoCompleteTextView) findViewById(R.id.main_header_search);
View line = findViewById(R.id.main_header_line);
fragment.setSearch(search);
fragment.setLine(line);
}
@Override
public void validationAvailable(List<String> items) {
mUiHandler.post(() -> {
List<Preference> list = getPreferenceList(getPreferenceScreen(), new ArrayList<>());
for (Preference p : list) {
if (p.getKey().endsWith(Constants.PREF_SUFFIX_ITEM) && p instanceof EditTextPreference) {
final EditText editText = ((EditTextPreference) p).getEditText();
if (editText instanceof AutoCompleteTextView) {
AutoCompleteTextView t = (AutoCompleteTextView) editText;
t.setAdapter(new ArrayAdapter<>(getActivity(), android.R.layout.simple_dropdown_item_1line, items));
t.performValidation();
}
}
}
});
}
/**
* Register the theme attributes with the default style for all the views extending
* {@link TextView} defined in Android SDK. You can use this method if you create an
* instance of {@code CustomTypeface}, and you want to configure with the default
* styles for the default android widgets.
*
* @param instance an instance of {@code CustomTypeface} to register the attributes
* @see #registerAttributeForDefaultStyle(Class, int)
*/
public static void registerAttributesForDefaultStyles(CustomTypeface instance) {
instance.registerAttributeForDefaultStyle(TextView.class, android.R.attr.textViewStyle);
instance.registerAttributeForDefaultStyle(EditText.class, android.R.attr.editTextStyle);
instance.registerAttributeForDefaultStyle(Button.class, android.R.attr.buttonStyle);
instance.registerAttributeForDefaultStyle(AutoCompleteTextView.class,
android.R.attr.autoCompleteTextViewStyle);
instance.registerAttributeForDefaultStyle(CheckBox.class, android.R.attr.checkboxStyle);
instance.registerAttributeForDefaultStyle(RadioButton.class,
android.R.attr.radioButtonStyle);
instance.registerAttributeForDefaultStyle(ToggleButton.class,
android.R.attr.buttonStyleToggle);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
instance.registerAttributeForDefaultStyle(CheckedTextView.class,
android.R.attr.checkedTextViewStyle);
}
}
@Override
protected void setUpView(View view) {
mRootView = view;
// from, to, amount edit text
AutoCompleteTextView etFrom = view.findViewById(R.id.et_from);
AutoCompleteTextView etTo = view.findViewById(R.id.et_to);
EditText etAmount = view.findViewById(R.id.et_amount);
// click handler
view.findViewById(R.id.btn_transfer).setOnClickListener(v -> onSend() );
etAmount.setOnEditorActionListener((textView, actionId, keyEvent) -> {
if (EditorInfo.IME_ACTION_SEND == actionId) {
onSend();
return true;
}
return false;
});
// account history
UiUtils.setupAccountHistory( etFrom, etTo );
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
View v = getCurrentFocus();
boolean ret = super.dispatchTouchEvent(event);
if (v instanceof AutoCompleteTextView) {
View currentFocus = getCurrentFocus();
int screenCoords[] = new int[2];
currentFocus.getLocationOnScreen(screenCoords);
float x = event.getRawX() + currentFocus.getLeft() - screenCoords[0];
float y = event.getRawY() + currentFocus.getTop() - screenCoords[1];
if (event.getAction() == MotionEvent.ACTION_UP
&& (x < currentFocus.getLeft() ||
x >= currentFocus.getRight() ||
y < currentFocus.getTop() ||
y > currentFocus.getBottom())) {
InputMethodManager imm =
(InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getWindow().getCurrentFocus().getWindowToken(), 0);
v.clearFocus();
}
}
return ret;
}
@Override
public boolean onMenuItemClick(MenuItem item)
{
TextInputLayout searchLayout = (TextInputLayout) activity.findViewById(R.id.search_input_layout);
AutoCompleteTextView searchText = (AutoCompleteTextView) activity.findViewById(R.id.search_input_text);
ImageButton cancel = (ImageButton) activity.findViewById(R.id.cancel_search);
searchLayout.setVisibility(View.VISIBLE);
cancel.setVisibility(View.VISIBLE);
if ( searchText.requestFocus() )
{
showKeyboard();
}
AutoCompleteTextView searchAutoCompleteTextView = (AutoCompleteTextView) activity.findViewById(R.id.search_input_text);
searchAutoCompleteTextView.setText(StringUtils.EMPTY);
return true;
}
private boolean validateForm() {
boolean result = true;
if (sms.getTimestampScheduled() < GregorianCalendar.getInstance().getTimeInMillis()) {
Toast.makeText(getApplicationContext(), getString(R.string.form_validation_datetime), Toast.LENGTH_SHORT).show();
result = false;
}
if (TextUtils.isEmpty(sms.getRecipientNumber())) {
((AutoCompleteTextView) findViewById(R.id.form_input_contact)).setError(getString(R.string.form_validation_contact));
result = false;
}
if (TextUtils.isEmpty(sms.getMessage())) {
((EditText) findViewById(R.id.form_input_message)).setError(getString(R.string.form_validation_message));
result = false;
}
return result;
}
@Override
public void onEditTextAttached(@NonNull TextInputLayout textInputLayout) {
AutoCompleteTextView autoCompleteTextView =
castAutoCompleteTextViewOrThrow(textInputLayout.getEditText());
setPopupBackground(autoCompleteTextView);
addRippleEffect(autoCompleteTextView);
setUpDropdownShowHideBehavior(autoCompleteTextView);
autoCompleteTextView.setThreshold(0);
autoCompleteTextView.removeTextChangedListener(exposedDropdownEndIconTextWatcher);
autoCompleteTextView.addTextChangedListener(exposedDropdownEndIconTextWatcher);
textInputLayout.setEndIconCheckable(true);
textInputLayout.setErrorIconDrawable(null);
textInputLayout.setTextInputAccessibilityDelegate(accessibilityDelegate);
textInputLayout.setEndIconVisible(true);
}
public void browse(View view) {
BrowseConfig config = new BrowseConfig();
config.typeFilter = "Public";
RadioButton radio = (RadioButton)findViewById(R.id.personalRadio);
if (radio.isChecked()) {
config.typeFilter = "Personal";
}
Spinner sortSpin = (Spinner)findViewById(R.id.sortSpin);
config.sort = (String)sortSpin.getSelectedItem();
AutoCompleteTextView tagText = (AutoCompleteTextView)findViewById(R.id.tagsText);
config.tag = (String)tagText.getText().toString();
AutoCompleteTextView categoryText = (AutoCompleteTextView)findViewById(R.id.categoriesText);
config.category = (String)categoryText.getText().toString();
EditText filterEdit = (EditText)findViewById(R.id.filterText);
config.filter = filterEdit.getText().toString();
CheckBox checkbox = (CheckBox)findViewById(R.id.imagesCheckBox);
MainActivity.showImages = checkbox.isChecked();
config.type = "Post";
if (MainActivity.instance != null) {
config.instance = MainActivity.instance.id;
}
HttpAction action = new HttpGetPostsAction(this, config);
action.execute();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.autocomplete_1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, COUNTRIES);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.edit);
textView.setAdapter(adapter);
}
/**
* Creates an adapter and sets it to an {@link AutoCompleteTextView} to enable suggestions.
*/
private void setUpAutoCompleteTextView() {
String[] completions = getResources().getStringArray(R.array.bodies_of_water);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_dropdown_item_1line,
completions);
AutoCompleteTextView autoComplete =
(AutoCompleteTextView) findViewById(R.id.auto_complete_text_view);
autoComplete.setAdapter(adapter);
}
private void setupWidgets() {
tagKeyLabelTextView = (TextView)rootView.findViewById(R.id.tagKeyLabelTextView);
tagKeyTextView = (TextView)rootView.findViewById(R.id.tagKeyTextView);
tagValueEditText = (AutoCompleteTextView)rootView.findViewById(R.id.tagValueEditText);
setupAutoComplete();
String keyLabel = tagEdit.getTagKeyLabel();
String key = tagEdit.getTagKey();
String val = tagEdit.getTagVal();
if (Constraints.singleton().tagIsRequired(key)) {
rootView.findViewById(R.id.requiredTextView).setVisibility(View.VISIBLE);
}
if (keyLabel != null) {
tagKeyLabelTextView.setText(keyLabel);
tagKeyTextView.setText(key);
} else {
tagKeyLabelTextView.setText(key);
tagKeyTextView.setText("");
}
tagValueEditText.setText(val);
tagEdit.setEditText(tagValueEditText);
if (Constraints.singleton().tagIsNumeric(key)) {
/**
* You could use Configuration.KEYBOARD_12KEY but this does not allow
* switching back to the normal alphabet keyboard. That needs to be
* an option.
*/
tagValueEditText.setRawInputType(Configuration.KEYBOARD_QWERTY);
}
}
private void writeValue() {
AutoCompleteTextView valueTextview = (AutoCompleteTextView) findViewById(R.id.storage_input);
final String value = valueTextview.getText().toString();
if (TextUtils.isEmpty(value)) {
valueTextview.setError(getString(R.string.error_field_required));
} else {
SharedPreferences prefs = getSharedPreferences(SIMPLE_STORAGE_PREFS, MODE_PRIVATE);
final String contractAddress = prefs.getString(CONTRACT_ADDRESS, null);
final SimpleOwnedStorage simpleOwnedStorage = ethereumAndroid.contracts().bind(contractAddress, CONTRACT_ABI, SimpleOwnedStorage.class);
Runnable writeTask = new Runnable() {
@Override
public void run() {
final PendingTransaction<Void> pendingWrite;
try {
pendingWrite = simpleOwnedStorage.set(value);
} catch (Exception e) {
showError(e);
return;
}
Runnable transactionTask = new Runnable() {
@Override
public void run() {
ethereumAndroid.submitTransaction(SimpleStorageActivity.this, REQUEST_CODE_WRITE, pendingWrite.getUnsignedTransaction());
}
};
SimpleStorageActivity.this.runOnUiThread(transactionTask);
}
};
new Thread(writeTask, "write contract data thread").start();
}
}
public void setContentView(View contentView)
{
ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
contentView.setLayoutParams(layoutParams);
if (contentView instanceof ListView)
{
setListViewHeightBasedOnChildren((ListView) contentView);
}
LinearLayout linearLayout = (LinearLayout) mAlertDialogWindow.findViewById(
R.id.message_content_view);
if (linearLayout != null)
{
linearLayout.removeAllViews();
linearLayout.addView(contentView);
}
for (int i = 0; i < (linearLayout != null ? linearLayout.getChildCount() : 0); i++)
{
if (linearLayout.getChildAt(i) instanceof AutoCompleteTextView)
{
AutoCompleteTextView autoCompleteTextView
= (AutoCompleteTextView) linearLayout.getChildAt(i);
autoCompleteTextView.setFocusable(true);
autoCompleteTextView.requestFocus();
autoCompleteTextView.setFocusableInTouchMode(true);
}
}
}
public void browse(View view) {
BrowseConfig config = new BrowseConfig();
config.typeFilter = "Public";
RadioButton radio = (RadioButton)findViewById(R.id.personalRadio);
if (radio.isChecked()) {
config.typeFilter = "Personal";
}
Spinner sortSpin = (Spinner)findViewById(R.id.sortSpin);
config.sort = (String)sortSpin.getSelectedItem();
AutoCompleteTextView tagText = (AutoCompleteTextView)findViewById(R.id.tagsText);
config.tag = (String)tagText.getText().toString();
AutoCompleteTextView categoryText = (AutoCompleteTextView)findViewById(R.id.categoriesText);
config.category = (String)categoryText.getText().toString();
EditText filterEdit = (EditText)findViewById(R.id.filterText);
config.filter = filterEdit.getText().toString();
CheckBox checkbox = (CheckBox)findViewById(R.id.imagesCheckBox);
MainActivity.showImages = checkbox.isChecked();
config.type = "Post";
if (MainActivity.instance != null) {
config.instance = MainActivity.instance.id;
}
HttpAction action = new HttpGetPostsAction(this, config);
action.execute();
}
private void initializeUi() {
setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
// Get the Layoutelements
mBtnConnect = (Button) findViewById(R.id.btnConnect);
mBtnConnect.setOnClickListener(oclConnect);
mBtnConnect.requestFocus();
mBtnClementine = (ImageButton) findViewById(R.id.btnClementineIcon);
mBtnClementine.setOnClickListener(oclClementine);
// Setup the animation for the Clementine icon
mAlphaDown = new AlphaAnimation(1.0f, 0.3f);
mAlphaUp = new AlphaAnimation(0.3f, 1.0f);
mAlphaDown.setDuration(ANIMATION_DURATION);
mAlphaUp.setDuration(ANIMATION_DURATION);
mAlphaDown.setFillAfter(true);
mAlphaUp.setFillAfter(true);
mAlphaUp.setAnimationListener(mAnimationListener);
mAlphaDown.setAnimationListener(mAnimationListener);
mAnimationCancel = false;
// Ip and Autoconnect
mEtIp = (AutoCompleteTextView) findViewById(R.id.etIp);
mEtIp.setRawInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
mEtIp.setThreshold(3);
// Get old ip and auto-connect from shared prefences
mEtIp.setText(mSharedPref.getString(SharedPreferencesKeys.SP_KEY_IP, ""));
mEtIp.setSelection(mEtIp.length());
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.select_dialog_item, mKnownIps.toArray(new String[0]));
mEtIp.setAdapter(adapter);
// Get the last auth code
mAuthCode = mSharedPref.getInt(SharedPreferencesKeys.SP_LAST_AUTH_CODE, 0);
}
private static void setText(AutoCompleteTextView view, CharSequence text, boolean filter) {
try {
Method method = AutoCompleteTextView.class.getMethod("setText", CharSequence.class, boolean.class);
method.setAccessible(true);
method.invoke(view, text, filter);
} catch (Exception e) {
//Fallback to public API which hopefully does mostly the same thing
view.setText(text);
}
}
public static void setHint(SearchView searchView, String hint, int resId, int color, Resources resources) {
AutoCompleteTextView autoComplete = (AutoCompleteTextView) findView(searchView, "mQueryTextView");
SpannableStringBuilder stopHint = new SpannableStringBuilder("");
stopHint.append(hint);
autoComplete.setHint(stopHint);
autoComplete.setHintTextColor(color);
}
@Override
public void addView(View child, int index, ViewGroup.LayoutParams params) {
if (child instanceof AutoCompleteTextView) {
setAutoCompleteTextView((AutoCompleteTextView) child);
super.addView(child, 0, params);
} else {
// Carry on adding the View...
super.addView(child, index, params);
}
}
@Test
public void testClearingTextInputHidesDropdownPopup() {
final Activity activity = activityTestRule.getActivity();
final AutoCompleteTextView editText = activity.findViewById(R.id.edittext_filled_editable);
onView(withId(R.id.edittext_filled_editable)).perform(typeText(INPUT_TEXT));
onView(withId(R.id.edittext_filled_editable)).perform(clearText());
assertThat(editText.isPopupShowing(), is(false));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_search, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView =
(SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setOnQueryTextListener(this);
searchView.setInputType(InputType.TYPE_TEXT_FLAG_CAP_WORDS);
searchView.setQuery(mPresenter.getSearchModels().get(0).getQuery(), false);
if (isInputMode) {
MenuItemCompat.expandActionView(searchItem);
} else {
MenuItemCompat.collapseActionView(searchItem);
}
MenuItemCompat.setOnActionExpandListener(searchItem, this);
AutoCompleteTextView autoCompleteTextView = searchView
.findViewById(android.support.v7.appcompat.R.id.search_src_text);
autoCompleteTextView.setThreshold(0);
autoCompleteTextView.setAdapter(new ArrayAdapter<>(this,
R.layout.layout_item_simple_list, mPresenter.getSearchRecordList()));
autoCompleteTextView.setDropDownBackgroundDrawable(new ColorDrawable(ViewUtils.getWindowBackground(getActivity())));
autoCompleteTextView.setOnItemClickListener((parent, view, position, id) -> {
onQueryTextSubmit(parent.getAdapter().getItem(position).toString());
});
return super.onCreateOptionsMenu(menu);
}
/**
* Builds the editor view.
*
* @param activity The activity on top of which the UI should be displayed.
* @param observerForTest Optional event observer for testing.
*/
public EditorView(Activity activity, PaymentRequestObserverForTest observerForTest) {
super(activity, R.style.FullscreenWhiteDialog);
mContext = activity;
mObserverForTest = observerForTest;
mHandler = new Handler();
mPhoneFormatterTask = new AsyncTask<Void, Void, PhoneNumberFormattingTextWatcher>() {
@Override
protected PhoneNumberFormattingTextWatcher doInBackground(Void... unused) {
return new PhoneNumberFormattingTextWatcher();
}
}.execute();
mEditorActionListener = new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
mDoneButton.performClick();
return true;
} else if (actionId == EditorInfo.IME_ACTION_NEXT) {
View next = v.focusSearch(View.FOCUS_FORWARD);
if (next != null && next instanceof AutoCompleteTextView) {
focusInputField(next);
return true;
}
}
return false;
}
};
}
@Test
public void setAutoCompleteListView_shouldHideListViewWhenQueryLosesFocus() throws Exception {
ListView listView = new ListView(ACTIVITY);
listView.setVisibility(VISIBLE);
peliasSearchView.setAutoCompleteListView(listView);
AutoCompleteTextView queryText = getQueryTextView();
shadowOf(queryText).setViewFocus(false);
assertThat(listView).isGone();
}
public void browse(View view) {
BrowseConfig config = new BrowseConfig();
config.typeFilter = "Public";
RadioButton radio = (RadioButton)findViewById(R.id.personalRadio);
if (radio.isChecked()) {
config.typeFilter = "Personal";
}
Spinner sortSpin = (Spinner)findViewById(R.id.sortSpin);
config.sort = (String)sortSpin.getSelectedItem();
AutoCompleteTextView tagText = (AutoCompleteTextView)findViewById(R.id.tagsText);
config.tag = tagText.getText().toString();
//AutoCompleteTextView categoryText = (AutoCompleteTextView)findViewById(R.id.categoriesText);
//config.category = categoryText.getText().toString();
EditText filterEdit = (EditText)findViewById(R.id.filterText);
config.filter = filterEdit.getText().toString();
//CheckBox checkbox = (CheckBox)findViewById(R.id.imagesCheckBox);
//MainActivity.showImages = checkbox.isChecked();
config.type = "Issue";
if (MainActivity.instance != null) {
config.instance = MainActivity.instance.id;
}
HttpAction action = new HttpGetIssuesAction(this, config);
action.execute();
}
public void browse(View view) {
BrowseConfig config = new BrowseConfig();
config.typeFilter = "Public";
RadioButton radio = (RadioButton)findViewById(R.id.personalRadio);
if (radio.isChecked()) {
config.typeFilter = "Personal";
}
Spinner sortSpin = (Spinner)findViewById(R.id.sortSpin);
config.sort = (String)sortSpin.getSelectedItem();
AutoCompleteTextView tagText = (AutoCompleteTextView)findViewById(R.id.tagsText);
config.tag = (String)tagText.getText().toString();
AutoCompleteTextView categoryText = (AutoCompleteTextView)findViewById(R.id.categoriesText);
config.category = (String)categoryText.getText().toString();
EditText filterEdit = (EditText)findViewById(R.id.filterText);
config.filter = filterEdit.getText().toString();
CheckBox checkbox = (CheckBox)findViewById(R.id.imagesCheckBox);
MainActivity.showImages = checkbox.isChecked();
config.type = "Post";
if (MainActivity.instance != null) {
config.instance = MainActivity.instance.id;
}
HttpAction action = new HttpGetPostsAction(this, config);
action.execute();
}
/**
* method to generate search suggestions for the AutoCompleteTextView from
* previously searched URLs
*/
private void initializeSearchSuggestions(final AutoCompleteTextView getUrl) {
mSuggestionsAdapter = new SuggestionsAdapter(this, mDarkTheme, isIncognito());
getUrl.setThreshold(1);
getUrl.setDropDownWidth(-1);
getUrl.setDropDownAnchor(R.id.toolbar_layout);
getUrl.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {
String url = null;
CharSequence urlString = ((TextView) view.findViewById(R.id.url)).getText();
if (urlString != null) {
url = urlString.toString();
}
if (url == null || url.startsWith(getString(R.string.suggestion))) {
CharSequence searchString = ((TextView) view.findViewById(R.id.title)).getText();
if (searchString != null) {
url = searchString.toString();
}
}
if (url == null) {
return;
}
getUrl.setText(url);
searchTheWeb(url);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getUrl.getWindowToken(), 0);
mPresenter.onAutoCompleteItemPressed();
}
});
getUrl.setSelectAllOnFocus(true);
getUrl.setAdapter(mSuggestionsAdapter);
}
private static void setText(AutoCompleteTextView view, CharSequence text, boolean filter) {
try {
Method method = AutoCompleteTextView.class.getMethod("setText", CharSequence.class, boolean.class);
method.setAccessible(true);
method.invoke(view, text, filter);
} catch (Exception e) {
//Fallback to public API which hopefully does mostly the same thing
view.setText(text);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String[] mCountries = getResources().getStringArray(R.array.country_names);
// Get a reference to the AutoCompleteTextView
final AutoCompleteTextView textView = findViewById(R.id.autocomplete_country);
// Create an ArrayAdapter containing country names
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
R.layout.list_item, mCountries);
// Set the adapter for the AutoCompleteTextView
textView.setAdapter(adapter);
// Display a Toast Message when the user clicks on an item in the AutoCompleteTextView
textView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
Toast.makeText(getApplicationContext(),
getString(R.string.winner_is_string, arg0.getAdapter().getItem(arg2)),
Toast.LENGTH_LONG).show();
textView.setText("");
}
});
}