`
bashenmail
  • 浏览: 228565 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

AutoCompleteTextView 实现汉字和拼音双向关联 只需改写ArrayAdapter

阅读更多

具体看代码:

 

public class CityAdapter<T> extends BaseAdapter implements Filterable {
	 /**
     * Contains the list of objects that represent the data of this ArrayAdapter.
     * The content of this list is referred to as "the array" in the documentation.
     */
    private List<T> mObjects;

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

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

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

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

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

    private Context mContext;    

    private ArrayList<T> mOriginalValues;
    private ArrayFilter mFilter;

    private LayoutInflater mInflater;

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

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

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

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

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

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

    /**
     * Adds the specified object at the end of the array.
     *
     * @param object The object to add at the end of the array.
     */
    public void add(T object) {
        if (mOriginalValues != null) {
            synchronized (mLock) {
                mOriginalValues.add(object);
                if (mNotifyOnChange) notifyDataSetChanged();
            }
        } else {
            mObjects.add(object);
            if (mNotifyOnChange) notifyDataSetChanged();
        }
    }

    /**
     * Inserts the specified object at the specified index in the array.
     *
     * @param object The object to insert into the array.
     * @param index The index at which the object must be inserted.
     */
    public void insert(T object, int index) {
        if (mOriginalValues != null) {
            synchronized (mLock) {
                mOriginalValues.add(index, object);
                if (mNotifyOnChange) notifyDataSetChanged();
            }
        } else {
            mObjects.add(index, object);
            if (mNotifyOnChange) notifyDataSetChanged();
        }
    }

    /**
     * Removes the specified object from the array.
     *
     * @param object The object to remove.
     */
    public void remove(T object) {
        if (mOriginalValues != null) {
            synchronized (mLock) {
                mOriginalValues.remove(object);
            }
        } else {
            mObjects.remove(object);
        }
        if (mNotifyOnChange) notifyDataSetChanged();
    }

    /**
     * Remove all elements from the list.
     */
    public void clear() {
        if (mOriginalValues != null) {
            synchronized (mLock) {
                mOriginalValues.clear();
            }
        } else {
            mObjects.clear();
        }
        if (mNotifyOnChange) notifyDataSetChanged();
    }

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

    /**
     * {@inheritDoc}
     */
    @Override
    public void notifyDataSetChanged() {
        super.notifyDataSetChanged();
        mNotifyOnChange = true;
    }

    /**
     * Control whether methods that change the list ({@link #add},
     * {@link #insert}, {@link #remove}, {@link #clear}) automatically call
     * {@link #notifyDataSetChanged}.  If set to false, caller must
     * manually call notifyDataSetChanged() to have the changes
     * reflected in the attached view.
     *
     * The default is true, and calling notifyDataSetChanged()
     * resets the flag to true.
     *
     * @param notifyOnChange if true, modifications to the list will
     *                       automatically call {@link
     *                       #notifyDataSetChanged}
     */
    public void setNotifyOnChange(boolean notifyOnChange) {
        mNotifyOnChange = notifyOnChange;
    }

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

    /**
     * Returns the context associated with this array adapter. The context is used
     * to create views from the resource passed to the constructor.
     *
     * @return The Context associated with this adapter.
     */
    public Context getContext() {
        return mContext;
    }

    /**
     * {@inheritDoc}
     */
    public int getCount() {
        return mObjects.size();
    }

    /**
     * {@inheritDoc}
     */
    public T getItem(int position) {
        return mObjects.get(position);
    }

    /**
     * Returns the position of the specified item in the array.
     *
     * @param item The item to retrieve the position of.
     *
     * @return The position of the specified item.
     */
    public int getPosition(T item) {
        return mObjects.indexOf(item);
    }

    /**
     * {@inheritDoc}
     */
    public long getItemId(int position) {
        return position;
    }

    /**
     * {@inheritDoc}
     */
    public View getView(int position, View convertView, ViewGroup parent) {
        return createViewFromResource(position, convertView, parent, mResource);
    }

    private View createViewFromResource(int position, View convertView, ViewGroup parent,
            int resource) {
        View view;
        TextView text;

        if (convertView == null) {
            view = mInflater.inflate(resource, parent, false);
        } else {
            view = convertView;
        }

        try {
            if (mFieldId == 0) {
                //  If no custom field is assigned, assume the whole resource is a TextView
                text = (TextView) view;
            } else {
                //  Otherwise, find the TextView field within the layout
                text = (TextView) view.findViewById(mFieldId);
            }
        } catch (ClassCastException e) {
            Log.e("ArrayAdapter", "You must supply a resource ID for a TextView");
            throw new IllegalStateException(
                    "ArrayAdapter requires the resource ID to be a TextView", e);
        }

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

        return view;
    }

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

    /**
     * {@inheritDoc}
     */
    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent) {
        return createViewFromResource(position, convertView, parent, mDropDownResource);
    }

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

    /**
     * {@inheritDoc}
     */
    public Filter getFilter() {
        if (mFilter == null) {
            mFilter = new ArrayFilter();
        }
        return mFilter;
    }

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

            if (mOriginalValues == null) {
                synchronized (mLock) {
                    mOriginalValues = new ArrayList<T>(mObjects);
                }
            }

            if (prefix == null || prefix.length() == 0) {
                synchronized (mLock) {
                    ArrayList<T> list = new ArrayList<T>(mOriginalValues);
                    results.values = list;
                    results.count = list.size();
                }
            } else {
                String prefixString = prefix.toString().toLowerCase();

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

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

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

                    final T value2 = mObjects2.get(i);
                    final String valueText2 = value2.toString().toLowerCase();
                    
                    //查找拼音 
                    if(valueText2.startsWith(prefixString)){
                    	newValues.add(value);
                    //查找汉字	
                    }else if(valueText.startsWith(prefixString)){
                    	newValues.add(value);
                    }else{
                    	
                    	//添加汉字关联
                    	final String[] words = valueText.split(" ");
                    	final int wordCount = words.length;
                    	
                    	for (int k = 0; k < wordCount; k++) {
                            if (words[k].startsWith(prefixString)) {
                                newValues.add(value);
                                break;
                            }
                        }
                    	
                    	//添加拼音关联汉字
                    	final String[] words2 = valueText2.split(" ");
                        final int wordCount2 = words2.length;

                        for (int k = 0; k < wordCount2; k++) {
                            if (words2[k].startsWith(prefixString)) {
                                newValues.add(value);
                                break;
                            }
                        }
                    	
                    }
                    
                }

                results.values = newValues;
                results.count = newValues.size();
            }

            return results;
        }

        @SuppressWarnings("unchecked")
		@Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            
            mObjects = (List<T>) results.values;
            if (results.count > 0) {
                notifyDataSetChanged();
            } else {
                notifyDataSetInvalidated();
            }
        }
    }
}

 调用代码如下:

 

cAdapter = new CityAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,汉字数组,拼音数组);
		
		autoView.setAdapter(cAdapter);
		autoView.setThreshold(1);

//其中 autoView 为 AutoCompleteTextView
效果图如下:



 

 
  • 大小: 17.5 KB
  • 大小: 15.7 KB
分享到:
评论
3 楼 liujunvy89 2011-09-27  
我怎么出现乱码
2 楼 xiaopei0714 2011-08-08  
表示假设我最初无法确定究竟有多少汉字跟别提找到对应的拼音数组(好比我们的通讯录),这样子要怎么实现?而且还有那种名字首字母匹配的,恳请赐教,拜托拜托
1 楼 forgottenp 2010-10-21  
非常好的东西啊,试试先。3Q

相关推荐

    AutoCompleteTextView汉字和拼音关联

    本知识点主要关注如何实现`AutoCompleteTextView`与汉字和拼音的关联,使得用户可以输入汉字或拼音进行查询。 首先,`AutoCompleteTextView` 是基于`EditText` 的扩展,提供了自动补全的功能。我们可以通过设置`...

    AutoCompleteTextView中文和拼音关联自动提示

    总的来说,实现`AutoCompleteTextView`的中文和拼音关联自动提示需要处理汉字到拼音的转换、自定义适配器以及监听输入事件。通过这样的方式,我们可以为用户提供更加智能和便捷的输入体验。在实际开发中,还可以根据...

    AutoCompleteTextView输入汉字拼音首字母实现过滤提示

    android API中的 AutoCompleteTextView组件只能匹配过滤纯英文或者纯汉字的 经过改进后可以输入 汉字拼音匹配汉字 类似于百度搜索 例如输入x 会匹配“迅雷”“迅速” 如果输入s 也可以匹配 “迅速”

    AutoCompleteTextView输入汉字拼音首字母实现过滤提示(支持多音字)2

    本篇文章将深入探讨如何实现一个能够处理汉字拼音首字母,并且支持多音字的AutoCompleteTextView过滤提示功能。 首先,我们要了解多音字的概念。在中文里,有些字有多个读音,例如“还”可以读作“hái”或“huán...

    AutoCompleteTextView输入汉字拼音首字母实现过滤提示(支持多音字)

    AutoCompleteTextView具有输入提示的功能,但是它的这种提示不适合对股票列表的过滤,如果你玩过股票软件,就会知道只要输入股票名称的首字母或股票代码就会出现符合匹配的股票,这种过滤怎么实现呢? 还有个问题,...

    Android之AutoCompleteTextView输入汉字拼音首字母实现过滤提示(支持多音字)

    可以参考下面博客:我的Android进阶之旅------&gt;Android之AutoCompleteTextView输入汉字拼音首字母实现过滤提示(支持多音字) (博客地址:http://blog.csdn.net/ouyang_peng/article/details/8826806)

    使用AutoCompleteTextView实现自动匹配输入的内容

    AutoCompleteTextView是Android SDK提供的一种视图组件,用于在用户输入文本时提供下拉列表的自动补全...通过分析和运行这个示例,你应该能更好地理解和掌握AutoCompleteTextView的用法,并将其应用到自己的项目中。

    AutoCompleteTextView实现历史记录功能

    4. 将适配器关联到AutoCompleteTextView:调用AutoCompleteTextView的setAdapter方法,传入适配器实例。 ```java searchView.setAdapter(adapter); ``` 5. 添加监听事件:为了在用户选择历史记录时更新界面,...

    android之自动填充框AutoCompleteTextView实现源码

    AutoCompleteTextView是Android系统提供的一种UI组件,它用于实现自动补全功能,常用于输入框中,当用户输入文本时,会根据已输入的内容显示匹配的建议列表。这个组件极大地提高了用户体验,尤其在处理大量可选项时...

    AutoCompleteTextView中输入字母或者汉字通过Filterable实现自动筛选提醒Demo

    总结起来,通过实现 `Filterable` 接口,我们可以自定义 `AutoCompleteTextView` 的数据过滤逻辑,从而实现根据用户输入的字母或汉字动态显示匹配的提示项。在实际开发中,可以根据具体需求调整过滤算法和 UI 设计,...

    AutoCompleteTextView和自定义的CursorAdapter

    这篇文章将深入探讨`AutoCompleteTextView` 的工作原理以及如何结合自定义的`CursorAdapter`来实现更灵活的数据绑定。 `AutoCompleteTextView`是`EditText`的一个子类,它可以动态地根据用户输入的内容展示下拉列表...

    AutoCompleteTextView

    这个简单的例子展示了如何利用自定义布局来实现AutoCompleteTextView的功能,使得用户界面更加灵活和个性化。 在Android应用设计中,AutoCompleteTextView常用于提升用户体验,比如在搜索框中,当用户开始输入时,...

    AutoCompleteTextView+SQLite实现自动检索

    下面我们将深入探讨如何利用`AutoCompleteTextView` 和SQLite来实现这一功能。 首先,我们要理解`AutoCompleteTextView`的工作原理。这个控件在用户输入时会触发一个监听事件,通过监听`TextWatcher`或`Adapter`的`...

    android中AutoCompleteTextView使用

    根据需求,可以自定义 `ArrayAdapter` 或 `CursorAdapter` 来实现更复杂的数据绑定和展示,比如使用自定义布局、添加图片等。 ### 五、实际应用 `AutoCompleteTextView` 和 `MultiAutoCompleteTextView` 广泛应用...

    TestCompleteText_AutoCompleteTextView和TextWatcher结合使用

    在Android开发中,AutoCompleteTextView和TextWatcher是两个非常重要的组件,它们可以帮助我们实现丰富的文本输入交互功能。本文将深入探讨这两个组件,并结合实例展示如何将它们结合起来使用,以实现关键词下拉提示...

    Android使用AutoCompleteTextView实现自动填充功能的案例

    "Android使用AutoCompleteTextView实现自动填充功能的案例" Android中的AutoCompleteTextView控件是实现自动填充功能的关键组件。下面我们将详细讲解如何使用AutoCompleteTextView实现自动填充功能。 ...

    自定义AutoCompleteTextView下拉列表控件

    在Android开发中,`AutoCompleteTextView` 是一个非常常见的组件,它用于实现自动补全功能,通常用于输入框中提供用户可能输入的建议。在给定的标题“自定义AutoCompleteTextView下拉列表控件”中,我们可以理解为...

    AutoCompleteTextView的简单使用

    AutoCompleteTextView是Android SDK提供的一种可以自动补全的文本输入框控件,它结合了EditText和ListView的功能,允许用户在输入时显示出与已输入内容匹配的建议列表。这个功能常见于许多应用程序,如搜索引擎、...

    AutoCompleteTextViewDemo

    AutoCompleteTextView是Android平台上一种非常实用的UI组件,主要用于实现自动补全或建议输入的功能。在给定的项目...通过理解其工作原理和实现细节,开发者可以更好地在自己的应用中实现类似的功能。

Global site tag (gtag.js) - Google Analytics