Android uses AutoCompleteTextView to Display Search history prompts

Source: Internet
Author: User

Introduction Google or Baidu is often used when we access the internet. If you enter the information we want in the input box, other prompts related to the information will appear, which is very convenient. This effect is implemented using AutoCompleteTextView in Android, and AutoCompleteTextView is an editable text view. When you type it, the suggestion information is displayed automatically. The suggestion list is displayed in the drop-down list box. You can select an item to replace the content in the edit box. When you click ENTER or click ENTER, the drop-down list automatically disappears. The recommended list is the data obtained from a data adapter. Step 1: Create a project AutoCompletestep2: design the application UI/layout/main. xml [html] <? Xml version = "1.0" encoding = "UTF-8"?> <LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android" android: orientation = "vertical" android: layout_width = "fill_parent" android: layout_height = "fill_parent"> <! -- When there is an EditText or AutoCompleteTextView, the focus is obtained by default when you enter the screen. To remove focus, add an o-pixel layout before auto and set it to get focus first. --> <LinearLayout android: layout_width = "0px" android: layout_height = "0px" android: focusable = "true" android: focusableInTouchMode = "true"> </LinearLayout> <! -- Define an Automatic completion text box, specify a character to input and prompt --> <AutoCompleteTextView android: id = "@ + id/auto" android: layout_width = "fill_parent" android: layout_height = "wrap_content" android: hint = "Enter Text to search" android: completionHint = "The Last Five Records" android: dropDownHorizontalOffset = "20dp" android: completionThreshold = "1" android: dropDownHeight = "fill_parent"/> <! -- Android: completionHint: The title displayed in the drop-down menu. android: completionThreshold: specifies the number of characters that the user must enter to display the android: dropDownHorizontalOffset prompt. By default, the drop-down menu is left aligned with the text box. android: dropDownVerticalOffset sets the vertical offset between the drop-down menu and text box. The drop-down menu is followed by the text box android: dropDownHeight by default. Set the height of the drop-down menu. android: dropDownWidth sets the width of the drop-down menu --> <Button android: text = "Search" android: id = "@ + id/search" android: layout_width = "wrap_content" android: layout_height = "wrap_content"/> </LinearLayout> Step 3: MainActivity. java [java] package cn. roco. autocomplete; import android. app. activity; import android. content. sharedPreferences; import android. OS. bundle; import android. view. V Iew; import android. view. view. onClickListener; import android. view. view. onFocusChangeListener; import android. widget. arrayAdapter; import android. widget. autoCompleteTextView; import android. widget. button; public class MainActivity extends Activity {private AutoCompleteTextView autoCompleteTextView; @ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); set ContentView (R. layout. main); autoCompleteTextView = (AutoCompleteTextView) findViewById (R. id. auto); initAutoComplete ("history", autoCompleteTextView); Button searchButton = (Button) findViewById (R. id. search); searchButton. setOnClickListener (new MyOnClickListener ();} private final class MyOnClickListener implements OnClickListener {@ Override public void onClick (View v) {saveHistory ("history", au ToCompleteTextView );}} /*** Save the content in the specified AutoCompleteTextView to the specified character segment in sharedPreference ** @ param field * The field name in the sharedPreference * @ param autoCompleteTextView * The AutoCompleteTextView */private void saveHistory (String field, autoCompleteTextView autoCompleteTextView) {String text = autoCompleteTextView. getText (). toString (); SharedPreferences sp = getSharedPreferences ("network_url", 0); String l Onghistory = sp. getString (field, "nothing"); if (! Longhistory. contains (text + ",") {StringBuilder sb = new StringBuilder (longhistory); sb. insert (0, text + ","); sp. edit (). putString ("history", sb. toString ()). commit () ;}/ *** initialize AutoCompleteTextView. A maximum of five prompts are displayed, the AutoCompleteTextView automatically prompts ** @ param field * field name saved in sharedPreference * @ param autoCompleteTextView * AutoCompleteTextView */private void initAutoComplete (String field, AutoC OmpleteTextView autoCompleteTextView) {SharedPreferences sp = getSharedPreferences ("network_url", 0); String longhistory = sp. getString ("history", "nothing"); String [] histories = longhistory. split (","); ArrayAdapter <String> adapter = new ArrayAdapter <String> (this, android. r. layout. simple_dropdown_item_1line, histories); // only keep the latest 50 records if (histories. length> 50) {String [] newHistories = new Str Ing [50]; System. arraycopy (histories, 0, newHistories, 0, 50); adapter = new ArrayAdapter <String> (this, android. r. layout. simple_dropdown_item_1line, newHistories);} autoCompleteTextView. setAdapter (adapter); autoCompleteTextView. setOnFocusChangeListener (new OnFocusChangeListener () {@ Override public void onFocusChange (View v, boolean hasFocus) {AutoCompleteTextView = (AutoCompleteTextView) v; If (hasFocus) {view. showDropDown () ;}}) ;}} Step 4: deploy the application to the simulator. Step 5: Enter the application several times and click search to save the history, exit the application and re-enter the application Step 6: this will automatically complete the search: Note: If you are familiar with android list development, you should be very familiar with the Adapter. The above instance code, the ArrayAdapter provided by android is used to bind the data and view to AutoCompleteTextView. We need to customize it from here. Like other adapers, the base class of ArrayAdapter is also a BaseAdapter. We can customize our own Adapter. But when there was a run, there was a response from wood, and there was no prompt? Indeed, our views and data are bound, but AutoCompleteTextView cannot obtain suitable data based on our Adapter, because the adapter does not meet the requirements! In turn, we will study the ArrayAdapter. In addition to being a sub-class of BaseAdapter, it also implements the Filterable interface! In AutoAdapter, we implement this interface and return a custom Filter. What kind of class does AutoMailFilter look like? First, let's take a closer look at how AutoCompleteTextView works. Right, it only filters and indexes some of the characters we enter and forms a view to feedback to our users, to improve our input efficiency! The next step is to build the core filter. AutoCompleteTextView will only receive the filtered data, so we will copy one more copy of the data source, one original copy, one copy is filtered: In AutoMailFilter, because of inheritance, we must implement two important methods: protected FilterResults using mfiltering (CharSequence prefix) to customize the filter policy in this method, the data is filtered based on the input prefix and assembled into FilterResults results and returned. The protected void publishResults (CharSequence constraint, FilterResults results) method is used for publishing results, after processing the results of the above method according to certain requirements, notify the Adapter to refresh the data view. Summary: According to AutoCompleteTextView It depends on two components, Adapter and Filter. One is view processing, and the other is data filtering processing. We can customize these two components as needed.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.