网上找到的都是同ArrayAdapter一起使用的,有时候需要自定义风格,咋办?follow me!
看上图,实现了清空输入框内容和删除Item功能。
其实使用AutoCompleteTextView就得实现过滤器Filterable,你得告诉它怎么过滤。由于ArrayAdapter已经
帮我们实现了Filterable接口,所以我们很容易忽略这个,以为AutoCompleteTextView用起来很简单。如果你使用的是
BaseAdapter呢?当然,事实上也不难,只要让它也实现Filterable接口就可以了。
下面是源码:
实现自定义的Adapter
- import java.util.ArrayList;
- import java.util.List;
- import qianlong.qlmobile.tablet.csco.R;
- import android.content.Context;
- import android.util.Log;
- import android.view.LayoutInflater;
- import android.view.View;
- import android.view.ViewGroup;
- import android.view.View.OnClickListener;
- import android.widget.BaseAdapter;
- import android.widget.Filter;
- import android.widget.Filterable;
- import android.widget.ImageView;
- import android.widget.TextView;
- public class AutoCompleteAdapter extends BaseAdapter implements Filterable{
- private Context context;
- private ArrayFilter mFilter;
- private ArrayList<String> mOriginalValues;//所有的Item
- private List<String> mObjects;//过滤后的item
- private final Object mLock = new Object();
- private int maxMatch=10;//最多显示多少个选项,负数表示全部
- public AutoCompleteAdapter(Context context,ArrayList<String> mOriginalValues,int maxMatch){
- this.context=context;
- this.mOriginalValues=mOriginalValues;
- this.maxMatch=maxMatch;
- }
- @Override
- public Filter getFilter() {
- // TODO Auto-generated method stub
- if (mFilter == null) {
- mFilter = new ArrayFilter();
- }
- return mFilter;
- }
- private class ArrayFilter extends Filter {
- @Override
- protected FilterResults performFiltering(CharSequence prefix) {
- // TODO Auto-generated method stub
- FilterResults results = new FilterResults();
- // if (mOriginalValues == null) {
- // synchronized (mLock) {
- // mOriginalValues = new ArrayList<String>(mObjects);//
- // }
- // }
- if (prefix == null || prefix.length() == 0) {
- synchronized (mLock) {
- Log.i("tag", "mOriginalValues.size="+mOriginalValues.size());
- ArrayList<String> list = new ArrayList<String>(mOriginalValues);
- results.values = list;
- results.count = list.size();
- return results;
- }
- } else {
- String prefixString = prefix.toString().toLowerCase();
- final int count = mOriginalValues.size();
- final ArrayList<String> newValues = new ArrayList<String>(count);
- for (int i = 0; i < count; i++) {
- final String value = mOriginalValues.get(i);
- final String valueText = value.toLowerCase();
- // if(valueText.contains(prefixString)){//匹配所有
- //
- // }
- // First match against the whole, non-splitted value
- 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;
- // }
- // }
- // }
- if(maxMatch>0){//有数量限制
- if(newValues.size()>maxMatch-1){//不要太多
- break;
- }
- }
- }
- results.values = newValues;
- results.count = newValues.size();
- }
- return results;
- }
- @Override
- protected void publishResults(CharSequence constraint,
- FilterResults results) {
- // TODO Auto-generated method stub
- mObjects = (List<String>) results.values;
- if (results.count > 0) {
- notifyDataSetChanged();
- } else {
- notifyDataSetInvalidated();
- }
- }
- }
- @Override
- public int getCount() {
- // TODO Auto-generated method stub
- return mObjects.size();
- }
- @Override
- public Object getItem(int position) {
- // TODO Auto-generated method stub
- //此方法有误,尽量不要使用
- return mObjects.get(position);
- }
- @Override
- public long getItemId(int position) {
- // TODO Auto-generated method stub
- return position;
- }
- @Override
- public View getView(final int position, View convertView, ViewGroup parent) {
- // TODO Auto-generated method stub
- ViewHolder holder = null;
- if(convertView==null){
- holder=new ViewHolder();
- LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
- convertView=inflater.inflate(R.layout.simple_list_item_for_autocomplete, null);
- holder.tv=(TextView)convertView.findViewById(R.id.simple_item_0);
- holder.iv=(ImageView)convertView.findViewById(R.id.simple_item_1);
- convertView.setTag(holder);
- }else{
- holder = (ViewHolder) convertView.getTag();
- }
- holder.tv.setText(mObjects.get(position));
- holder.iv.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- // TODO Auto-generated method stub
- String obj=mObjects.remove(position);
- mOriginalValues.remove(obj);
- notifyDataSetChanged();
- }
- });
- return convertView;
- }
- class ViewHolder {
- TextView tv;
- ImageView iv;
- }
- public ArrayList<String> getAllItems(){
- return mOriginalValues;
- }
- }
- import android.content.Context;
- import android.util.AttributeSet;
- import android.view.View;
- import android.widget.AutoCompleteTextView;
- import android.widget.ImageView;
- import android.widget.RelativeLayout;
- import android.widget.ImageView.ScaleType;
- public class AdvancedAutoCompleteTextView extends RelativeLayout{
- private Context context;
- private AutoCompleteTextView tv;
- public AdvancedAutoCompleteTextView(Context context) {
- super(context);
- // TODO Auto-generated constructor stub
- this.context=context;
- }
- public AdvancedAutoCompleteTextView(Context context, AttributeSet attrs) {
- super(context, attrs);
- // TODO Auto-generated constructor stub
- this.context=context;
- }
- @Override
- protected void onFinishInflate() {
- super.onFinishInflate();
- initViews();
- }
- private void initViews() {
- RelativeLayout.LayoutParams params=new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
- tv=new AutoCompleteTextView(context);
- tv.setLayoutParams(params);
- tv.setPadding(10, 0, 40, 0);
- // tv.setSingleLine(true);
- RelativeLayout.LayoutParams p=new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
- p.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
- p.addRule(RelativeLayout.CENTER_VERTICAL);
- p.rightMargin=10;
- ImageView iv=new ImageView(context);
- iv.setLayoutParams(p);
- iv.setScaleType(ScaleType.FIT_CENTER);
- iv.setImageResource(R.drawable.delete);
- iv.setClickable(true);
- iv.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- // TODO Auto-generated method stub
- tv.setText("");
- }
- });
- this.addView(tv);
- this.addView(iv);
- }
- public void setAdapter(AutoCompleteAdapter adapter){
- tv.setAdapter(adapter);
- }
- public void setThreshold(int threshold){
- tv.setThreshold(threshold);
- }
- public AutoCompleteTextView getAutoCompleteTextView(){
- return tv;
- }
- }
simple_list_item_for_autocomplete.xml
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:orientation="horizontal"
- android:paddingTop="5dip"
- android:paddingBottom="5dip"
- >
- <TextView android:id="@+id/simple_item_0"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:layout_weight="1"
- android:paddingLeft="5dip"
- android:textColor="@android:color/black"
- />
- <ImageView android:id="@+id/simple_item_1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:scaleType="fitCenter"
- android:src="@drawable/delete"
- android:layout_centerVertical="true"
- android:layout_marginRight="5dip"
- />
- </LinearLayout>
使用,通常情况下都这样:
- private AdvancedAutoCompleteTextView tv;
- private AutoCompleteAdapter adapter;
- private ArrayList<String> mOriginalValues=new ArrayList<String>();
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- mOriginalValues.add("1234561");
- mOriginalValues.add("1234562");
- mOriginalValues.add("2234563");
- mOriginalValues.add("2234564");
- mOriginalValues.add("3234561111");
- mOriginalValues.add("32345622222");
- mOriginalValues.add("323456333333");
- mOriginalValues.add("3234564444");
- mOriginalValues.add("3234565555");
- mOriginalValues.add("32345666666");
- mOriginalValues.add("32345777777");
- tv = (AdvancedAutoCompleteTextView) findViewById(R.id.tv);
- tv.setThreshold(0);
- adapter = new AutoCompleteAdapter(this, mOriginalValues, 10);
- tv.setAdapter(adapter);
- }
这是arrayAdapter自定义的一个私有内部类,所谓私有,就意味着你不能通过 继承去修改这种过滤方法,同样你也不能直接得到他过滤后结果集results。假如你想使用新的过滤方法,你必须重写getfilter()方法,返回的 filter对象是你要新建的filter对象(在里面包含performFiltering()方法重新构造你要的过滤方法)
2.setDropDownHeight方法 ,用来设置提示下拉框的高度,注意,这只是限制了提示下拉框的高度,提示数据集的个数并没有变化
3.setThreshold方法,设置从输入第几个字符起出现提示
4.setCompletionHint方法,设置提示框最下面显示的文字
5.setOnFocusChangeListener方法,里面包含OnFocusChangeListener监听器,设置焦点改变事件
6.showdropdown方法,让下拉框弹出来
我没有用到的一些方法列举
1.clearListSelection,去除selector样式,只是暂时的去除,当用户再输入时又重新出现
2.dismissDropDown,关闭下拉提示框
3.enoughToFilter,这是一个是否满足过滤条件的方法,sdk建议我们可以重写这个方法
4. getAdapter,得到一个可过滤的列表适配器
5.getDropDownAnchor,得到下拉框的锚计的view的id
6.getDropDownBackground,得到下拉框的背景色
7.setDropDownBackgroundDrawable,设置下拉框的背景色
8.setDropDownBackgroundResource,设置下拉框的背景资源
9.setDropDownVerticalOffset,设置下拉表垂直偏移量,即是list里包含的数据项数目
10.getDropDownVerticalOffset ,得到下拉表垂直偏移量
11..setDropDownHorizontalOffset,设置水平偏移量
12.setDropDownAnimationStyle,设置下拉框的弹出动画
13.getThreshold,得到过滤字符个数
14.setOnItemClickListener,设置下拉框点击事件
15.getListSelection,得到下拉框选中为位置
16.getOnItemClickListener。得到单项点击事件
17.getOnItemSelectedListener得到单项选中事件
18.getAdapter,得到那个设置的适配器
一些隐藏方法和构造我没有列举了,具体可以参考api文档
<AutoCompleteTextView
android:id="@+id/input_city_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="@string/city_select_hint"
android:gravity="center"
android:maxLength="5"
android:completionThreshold="1"
android:popupBackground="@color/stroke_green"
android:background="@drawable/edittext_shape"/>
里面的android:popupBackground就是设置下拉框的背景色。
android:completionHint | 设置出现在下拉菜单中的提示标题 |
android:completionThreshold | 设置用户至少输入多少个字符才会显示提示 |
android:dropDownHorizontalOffset | 下拉菜单于文本框之间的水平偏移。默认与文本框左对齐 |
android:dropDownHeight | 下拉菜单的高度 |
android:dropDownWidth | 下拉菜单的宽度 |
android:singleLine |
单行显示 |
android:dropDownVerticalOffset |
垂直偏移量 |