`

AutoCompleteTextView

阅读更多
  1. public class CityAdapter<T> extends BaseAdapter implements Filterable {
  2.         /**
  3.     * Contains the list of objects that represent the data of this ArrayAdapter .
  4.     * The content of this list is referred to as "the array" in the documentation.
  5.     */
  6.     private List<T> mObjects;

  7.     private List<T> mObjects2;
  8.    
  9.     /**
  10.     * Lock used to modify the content of {@link #mObjects}. Any write operation
  11.     * performed on the array should be synchronized on this lock. This lock is also
  12.     * used by the filter (see {@link #getFilter()} to make a synchronized copy of
  13.     * the original array of data.
  14.     */
  15.     private final Object mLock = new Object();

  16.     /**
  17.     * The resource indicating what views to inflate to display the content of this
  18.     * array adapter.
  19.     */
  20.     private int mResource;

  21.     /**
  22.     * The resource indicating what views to inflate to display the content of this
  23.     * array adapter in a drop down widget.
  24.     */
  25.     private int mDropDownResource;

  26.     /**
  27.     * If the inflated resource is not a TextView, {@link #mFieldId} is used to find
  28.     * a TextView inside the inflated views hierarchy. This field must contain the
  29.     * identifier that matches the one defined in the resource file.
  30.     */
  31.     private int mFieldId = 0;

  32.     /**
  33.     * Indicates whether or not {@link #notifyDataSetChanged()} must be called whenever
  34.     * {@link #mObjects} is modified.
  35.     */
  36.     private boolean mNotifyOnChange = true;

  37.     private Context mContext;   

  38.     private ArrayList<T> mOriginalValues;
  39.     private ArrayFilter mFilter;

  40.     private LayoutInflater mInflater;

  41.     /**
  42.     * Constructor
  43.     *
  44.     * @param context The current context.
  45.     * @param textViewResourceId The resource ID for a layout file containing a TextView to use when
  46.     *                instantiating views.
  47.     */
  48.     public CityAdapter(Context context, int textViewResourceId) {
  49.         init(context, textViewResourceId, 0, new ArrayList<T>(),new ArrayList<T>());
  50.     }

  51.     /**
  52.     * Constructor
  53.     *
  54.     * @param context The current context.
  55.     * @param resource The resource ID for a layout file containing a layout to use when
  56.     *                instantiating views.
  57.     * @param textViewResourceId The id of the TextView within the layout resource to be populated
  58.     */
  59.     public CityAdapter(Context context, int resource, int textViewResourceId) {
  60.         init(context, resource, textViewResourceId, new ArrayList<T>(),new ArrayList<T>());
  61.     }

  62.     /**
  63.     * Constructor
  64.     *
  65.     * @param context The current context.
  66.     * @param textViewResourceId The resource ID for a layout file containing a TextView to use when
  67.     *                instantiating views.
  68.     * @param objects The objects to represent in the ListView.
  69.     * @param objects2 城市拼音数组
  70.     */
  71.     public CityAdapter(Context context, int textViewResourceId, T[] objects,T[] objects2) {
  72.         init(context, textViewResourceId, 0, Arrays.asList(objects),Arrays.asList(objects2));
  73.     }

  74.     /**
  75.     * Constructor
  76.     *
  77.     * @param context The current context.
  78.     * @param resource The resource ID for a layout file containing a layout to use when
  79.     *                instantiating views.
  80.     * @param textViewResourceId The id of the TextView within the layout resource to be populated
  81.     * @param objects The objects to represent in the ListView.
  82.     */
  83.     public CityAdapter(Context context, int resource, int textViewResourceId, T[] objects,T[] objects2) {
  84.         init(context, resource, textViewResourceId, Arrays.asList(objects),Arrays.asList(objects2));
  85.     }

  86.     /**
  87.     * Constructor
  88.     *
  89.     * @param context The current context.
  90.     * @param textViewResourceId The resource ID for a layout file containing a TextView to use when
  91.     *                instantiating views.
  92.     * @param objects The objects to represent in the ListView.
  93.     */
  94.     public CityAdapter(Context context, int textViewResourceId, List<T> objects,List<T> objects2) {
  95.         init(context, textViewResourceId, 0, objects,objects2);
  96.     }

  97.     /**
  98.     * Constructor
  99.     *
  100.     * @param context The current context.
  101.     * @param resource The resource ID for a layout file containing a layout to use when
  102.     *                instantiating views.
  103.     * @param textViewResourceId The id of the TextView within the layout resource to be populated
  104.     * @param objects The objects to represent in the ListView.
  105.     */
  106.     public CityAdapter(Context context, int resource, int textViewResourceId, List<T> objects,List<T> objects2) {
  107.         init(context, resource, textViewResourceId, objects, objects2);
  108.     }

  109.     /**
  110.     * Adds the specified object at the end of the array.
  111.     *
  112.     * @param object The object to add at the end of the array.
  113.     */
  114.     public void add(T object) {
  115.         if (mOriginalValues != null) {
  116.             synchronized (mLock) {
  117.                 mOriginalValues.add(object);
  118.                 if (mNotifyOnChange) notifyDataSetChanged();
  119.             }
  120.         } else {
  121.             mObjects.add(object);
  122.             if (mNotifyOnChange) notifyDataSetChanged();
  123.         }
  124.     }

  125.     /**
  126.     * Inserts the specified object at the specified index in the array.
  127.     *
  128.     * @param object The object to insert into the array.
  129.     * @param index The index at which the object must be inserted.
  130.     */
  131.     public void insert(T object, int index) {
  132.         if (mOriginalValues != null) {
  133.             synchronized (mLock) {
  134.                 mOriginalValues.add(index, object);
  135.                 if (mNotifyOnChange) notifyDataSetChanged();
  136.             }
  137.         } else {
  138.             mObjects.add(index, object);
  139.             if (mNotifyOnChange) notifyDataSetChanged();
  140.         }
  141.     }

  142.     /**
  143.     * Removes the specified object from the array.
  144.     *
  145.     * @param object The object to remove.
  146.     */
  147.     public void remove(T object) {
  148.         if (mOriginalValues != null) {
  149.             synchronized (mLock) {
  150.                 mOriginalValues.remove(object);
  151.             }
  152.         } else {
  153.             mObjects.remove(object);
  154.         }
  155.         if (mNotifyOnChange) notifyDataSetChanged();
  156.     }

  157.     /**
  158.     * Remove all elements from the list.
  159.     */
  160.     public void clear() {
  161.         if (mOriginalValues != null) {
  162.             synchronized (mLock) {
  163.                 mOriginalValues.clear();
  164.             }
  165.         } else {
  166.             mObjects.clear();
  167.         }
  168.         if (mNotifyOnChange) notifyDataSetChanged();
  169.     }

  170.     /**
  171.     * Sorts the content of this adapter using the specified comparator.
  172.     *
  173.     * @param comparator The comparator used to sort the objects contained
  174.     *        in this adapter.
  175.     */
  176.     public void sort(Comparator<? super T> comparator) {
  177.         Collections.sort(mObjects, comparator);
  178.         if (mNotifyOnChange) notifyDataSetChanged();       
  179.     }

  180.     /**
  181.     * {@inheritDoc}
  182.     */
  183.     @Override
  184.     public void notifyDataSetChanged() {
  185.         super.notifyDataSetChanged();
  186.         mNotifyOnChange = true;
  187.     }

  188.     /**
  189.     * Control whether methods that change the list ({@link #add},
  190.     * {@link #insert}, {@link #remove}, {@link #clear}) automatically call
  191.     * {@link #notifyDataSetChanged}.  If set to false, caller must
  192.     * manually call notifyDataSetChanged() to have the changes
  193.     * reflected in the attached view.
  194.     *
  195.     * The default is true, and calling notifyDataSetChanged()
  196.     * resets the flag to true.
  197.     *
  198.     * @param notifyOnChange if true, modifications to the list will
  199.     *                      automatically call {@link
  200.     *                      #notifyDataSetChanged}
  201.     */
  202.     public void setNotifyOnChange(boolean notifyOnChange) {
  203.         mNotifyOnChange = notifyOnChange;
  204.     }

  205.     private void init(Context context, int resource, int textViewResourceId, List<T> objects ,List<T> objects2) {
  206.         mContext = context;
  207.         mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  208.         mResource = mDropDownResource = resource;
  209.         mObjects = objects;
  210.         mObjects2 = objects2;
  211.         mFieldId = textViewResourceId;
  212.     }

  213.     /**
  214.     * Returns the context associated with this array adapter. The context is used
  215.     * to create views from the resource passed to the constructor.
  216.     *
  217.     * @return The Context associated with this adapter.
  218.     */
  219.     public Context getContext() {
  220.         return mContext;
  221.     }

  222.     /**
  223.     * {@inheritDoc}
  224.     */
  225.     public int getCount() {
  226.         return mObjects.size();
  227.     }

  228.     /**
  229.     * {@inheritDoc}
  230.     */
  231.     public T getItem(int position) {
  232.         return mObjects.get(position);
  233.     }

  234.     /**
  235.     * Returns the position of the specified item in the array.
  236.     *
  237.     * @param item The item to retrieve the position of.
  238.     *
  239.     * @return The position of the specified item.
  240.     */
  241.     public int getPosition(T item) {
  242.         return mObjects.indexOf(item);
  243.     }

  244.     /**
  245.     * {@inheritDoc}
  246.     */
  247.     public long getItemId(int position) {
  248.         return position;
  249.     }

  250.     /**
  251.     * {@inheritDoc}
  252.     */
  253.     public View getView(int position, View convertView, ViewGroup parent) {
  254.         return createViewFromResource(position, convertView, parent, mResource);
  255.     }

  256.     private View createViewFromResource(int position, View convertView, ViewGroup parent,
  257.             int resource) {
  258.         View view;
  259.         TextView text;

  260.         if (convertView == null) {
  261.             view = mInflater.inflate(resource, parent, false);
  262.         } else {
  263.             view = convertView;
  264.         }

  265.         try {
  266.             if (mFieldId == 0) {
  267.                 //  If no custom field is assigned, assume the whole resource is a TextView
  268.                 text = (TextView) view;
  269.             } else {
  270.                 //  Otherwise, find the TextView field within the layout
  271.                 text = (TextView) view.findViewById(mFieldId);
  272.             }
  273.         } catch (ClassCastException e) {
  274.             Log.e("ArrayAdapter", "You must supply a resource ID for a TextView");
  275.             throw new IllegalStateException(
  276.                     "ArrayAdapter requires the resource ID to be a TextView", e);
  277.         }

  278.         text.setText(getItem(position).toString());

  279.         return view;
  280.     }

  281.     /**
  282.     * <p>Sets the layout resource to create the drop down views.</p>
  283.     *
  284.     * @param resource the layout resource defining the drop down views
  285.     * @see #getDropDownView(int, android.view.View, android.view.ViewGroup)
  286.     */
  287.     public void setDropDownViewResource(int resource) {
  288.         this.mDropDownResource = resource;
  289.     }

  290.     /**
  291.     * {@inheritDoc}
  292.     */
  293.     @Override
  294.     public View getDropDownView(int position, View convertView, ViewGroup parent) {
  295.         return createViewFromResource(position, convertView, parent, mDropDownResource);
  296.     }

  297.     /**
  298.     * Creates a new ArrayAdapter from external resources. The content of the array is
  299.     * obtained through {@link android.content.res.Resources#getTextArray(int)}.
  300.     *
  301.     * @param context The application's environment.
  302.     * @param textArrayResId The identifier of the array to use as the data source.
  303.     * @param textViewResId The identifier of the layout used to create views.
  304.     *
  305.     * @return An ArrayAdapter<CharSequence>.
  306.     */
  307.     public static ArrayAdapter<CharSequence> createFromResource(Context context,
  308.             int textArrayResId, int textViewResId) {
  309.         CharSequence[] strings = context.getResources().getTextArray(textArrayResId);
  310.         return new ArrayAdapter<CharSequence>(context, textViewResId, strings);
  311.     }

  312.     /**
  313.     * {@inheritDoc}
  314.     */
  315.     public Filter getFilter() {
  316.         if (mFilter == null) {
  317.             mFilter = new ArrayFilter();
  318.         }
  319.         return mFilter;
  320.     }

  321.     /**
  322.     * <p>An array filter constrains the content of the array adapter with
  323.     * a prefix. Each item that does not start with the supplied prefix
  324.     * is removed from the list.</p>
  325.     */
  326.     private class ArrayFilter extends Filter {
  327.         @Override
  328.         protected FilterResults performFiltering(CharSequence prefix) {
  329.             FilterResults results = new FilterResults();

  330.             if (mOriginalValues == null) {
  331.                 synchronized (mLock) {
  332.                     mOriginalValues = new ArrayList<T>(mObjects);
  333.                 }
  334.             }

  335.             if (prefix == null || prefix.length() == 0) {
  336.                 synchronized (mLock) {
  337.                     ArrayList<T> list = new ArrayList<T>(mOriginalValues);
  338.                     results.values = list;
  339.                     results.count = list.size();
  340.                 }
  341.             } else {
  342.                 String prefixString = prefix.toString().toLowerCase();

  343.                 final ArrayList<T> values = mOriginalValues;
  344.                 final int count = values.size();

  345.                 final ArrayList<T> newValues = new ArrayList<T>(count);

  346.                 for (int i = 0; i < count; i++) {
  347.                     final T value = values.get(i);
  348.                     final String valueText = value.toString().toLowerCase();

  349.                     final T value2 = mObjects2.get(i);
  350.                     final String valueText2 = value2.toString().toLowerCase();
  351.                    
  352.                     //查找拼音
  353.                     if(valueText2.startsWith(prefixString)){
  354.                             newValues.add(value);
  355.                     //查找汉字       
  356.                     }else if(valueText.startsWith(prefixString)){
  357.                             newValues.add(value);
  358.                     }else{
  359.                            
  360.                             //添加汉字关联
  361.                             final String[] words = valueText.split(" ");
  362.                             final int wordCount = words.length;
  363.                            
  364.                             for (int k = 0; k < wordCount; k++) {
  365.                             if (words[k].startsWith(prefixString)) {
  366.                                 newValues.add(value);
  367.                                 break;
  368.                             }
  369.                         }
  370.                            
  371.                             //添加拼音关联汉字
  372.                             final String[] words2 = valueText2.split(" ");
  373.                         final int wordCount2 = words2.length;

  374.                         for (int k = 0; k < wordCount2; k++) {
  375.                             if (words2[k].startsWith(prefixString)) {
  376.                                 newValues.add(value);
  377.                                 break;
  378.                             }
  379.                         }
  380.                            
  381.                     }
  382.                    
  383.                 }

  384.                 results.values = newValues;
  385.                 results.count = newValues.size();
  386.             }

  387.             return results;
  388.         }

  389.         @SuppressWarnings("unchecked")
  390.                 @Override
  391.         protected void publishResults(CharSequence constraint, FilterResults results) {
  392.            
  393.             mObjects = (List<T>) results.values;
  394.             if (results.count > 0) {
  395.                 notifyDataSetChanged();
  396.             } else {
  397.                 notifyDataSetInvalidated();
  398.             }
  399.         }
  400.     }
  401. }

 

 

  1. cAdapter = new CityAdapter<String>(this,android.R.layout.simple_dropdown_item_1line, 汉字数组,拼音数组); 
  2. autoView.setAdapter(cAdapter); 
  3. autoView.setThreshold(1);   
  4. //其中 autoView 为 AutoCompleteTextView
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics