`

AutoCompleteTextView customize dropdown

 
阅读更多

NameAdapter.java:

package com.eoemobile.book.ex_widgetdemo;

import java.util.ArrayList;  
import java.util.List;  
  
import android.content.Context;  
import android.view.View;  
import android.view.ViewGroup;  
import android.widget.BaseAdapter;  
import android.widget.Filter;  
import android.widget.Filterable;  
import android.widget.TextView; 

import android.widget.ListView;
import android.graphics.drawable.ColorDrawable;
import android.graphics.Color;

public class NameAdapter extends BaseAdapter implements Filterable {  
    private ArrayFilter mFilter;  
    private List<String> mList;  
    private Context context;  
    private ArrayList<String> mUnfilteredData;  
      
    public NameAdapter(List<String> mList, Context context) {  
        this.mList = mList;  
        this.context = context;  
    }  
    
    public int getCount() {  
        return mList==null ? 0:mList.size();  
    }  
    
    public Object getItem(int position) {  
        return mList.get(position);  
    }  
    
    public long getItemId(int position) {  
        return position;  
    }  
    /*
     * Is it possible to remove/change color of the delimiter(it's grey by
     default) in AutoCompleteTextView's popup ? In ListView I get use of the
     "delimiter" parameter, but I haven't found any similar in
     AutoCompleteTextView.
     * */
    public View getView(int position, View convertView, ViewGroup parent) {  
        View view;  
        ViewHolder holder;  
        if(convertView==null){  
            view = View.inflate(context, R.layout.name_item, null);                
            holder = new ViewHolder();  
            holder.tv_name = (TextView) view.findViewById(R.id.tv_name);              
            view.setTag(holder);  
        }else{  
            view = convertView;  
            holder = (ViewHolder) view.getTag();  
        }  
        
        if(parent!=null&&(parent instanceof ListView)){
          ListView lv=null;
          try{
            lv=(ListView)parent;
          }catch(Exception e){}
          if(lv!=null){
          	  //从源代码看,只要调用了ListView的setDivider接口,mDividerHeight就会被置为0或-1,
          	  //所以你根本看不到线,如果想看到线,就要把调用顺序反过来,如下
              lv.setDivider(new ColorDrawable(Color.GRAY));
              lv.setDividerHeight(1);
          }
        }
          
        String keyword = mList.get(position);          
        holder.tv_name.setText(keyword);  
        return view;  
    }  
      
    static class ViewHolder{  
        public TextView tv_name; 
    }  
    
    public Filter getFilter() {  
        if (mFilter == null) {  
            mFilter = new ArrayFilter();  
        }  
        return mFilter;  
    }  
  
    private class ArrayFilter extends Filter {  
  
        @Override  
        protected FilterResults performFiltering(CharSequence prefix) {  
            FilterResults results = new FilterResults();  
  
            if (mUnfilteredData == null) {  
                mUnfilteredData = new ArrayList<String>(mList);  
            }  
  
            if (prefix == null || prefix.length() == 0) {  
                ArrayList<String> list = mUnfilteredData;  
                results.values = list;  
                results.count = list.size();  
            } else {  
                String prefixString = prefix.toString().toLowerCase();  
                ArrayList<String> unfilteredValues = mUnfilteredData;  
                int count = unfilteredValues.size();  
  
                ArrayList<String> newValues = new ArrayList<String>(count);  
                for (int i = 0; i < count; i++) {  
                	String keyword = unfilteredValues.get(i);  
                    if (!keyword.equals("")) {                            
                        if(!keyword.equals("") && keyword.startsWith(prefixString)){                                
                            newValues.add(keyword);  
                        } 
                    }  
                }  
  
                results.values = newValues;  
                results.count = newValues.size();  
            }  
  
            return results;  
        }  
  
        @Override  
        protected void publishResults(CharSequence constraint,FilterResults results) {  
             //no inspection unchecked  
            mList = (List<String>) results.values;  
            if (results.count > 0) {  
                notifyDataSetChanged();  
            } else {  
                notifyDataSetInvalidated();  
            }  
        }  
          
    }  
}  

 

AutoCompleteTextViewActivity.java

package com.eoemobile.book.ex_widgetdemo;

import java.util.ArrayList;  
import java.util.List;
//import java.util.Map;

import android.os.Bundle;  
import android.app.Activity;
//import android.view.Menu;  
import android.view.View;  
import android.widget.AdapterView;  
import android.widget.AdapterView.OnItemClickListener;  
import android.widget.AutoCompleteTextView;
//import android.widget.ArrayAdapter;
import android.util.Log;
import android.view.WindowManager;
//import android.view.KeyEvent;
import android.view.inputmethod.InputMethodManager;
import android.content.Context;
import android.widget.LinearLayout;
import android.widget.Button;

public class AutoCompleteTextViewActivity extends Activity implements OnItemClickListener {
	List<String> mList;
	private AutoCompleteTextView textView;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.autocomplete);
        setTitle("AutoCompleteTextViewActivity");
        /*C:\Program Files\Android\android-sdk\platforms\android-19\data\res\layout
        R.layout.simple_dropdown_item_1line来源于此
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
        android.R.layout.simple_dropdown_item_1line, KEYWORDS);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>  
        (this,android.R.layout.select_dialog_item, KEYWORDS);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.activity_complete_new_style,KEYWORDS);
        */
        buildAppData();  
        findView();
        setGoBack();
    }
    
    /*@Override
    public void onBackPressed()  {
      Log.i("AutoCompleteTextViewActivity","onBackPressed");
      InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
      imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
      return;      
    }*/
    
    private void setGoBack(){
    	Button back=(Button)findViewById(R.id.back);
    	back.setOnClickListener(mGoBack);
    }
    
    private Button.OnClickListener mGoBack=new Button.OnClickListener(){
    	public void onClick(View v){
    		finish();
    	}
    };
    
    private AutoCompleteTextView.OnDismissListener dismissListener=new AutoCompleteTextView.OnDismissListener(){
  		public void onDismiss(){
  			View view = getCurrentFocus();
  			if(view != null) {  
  			  InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
  			  imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
  			}
  		}
  	};
  	
    private void buildAppData(){
      mList=new ArrayList<String>();
      for(int i=0;i<KEYWORDS.length;i++){
    	mList.add(KEYWORDS[i]);
      }
    }
	
    private void findView(){
      textView = (AutoCompleteTextView) findViewById(R.id.auto_complete);
      NameAdapter mAdapter =new NameAdapter(mList, getApplicationContext());
      textView.setAdapter(mAdapter);
      textView.setOnItemClickListener(this);
      
      WindowManager wm = this.getWindowManager();
      int width = wm.getDefaultDisplay().getWidth();
      //int height = wm.getDefaultDisplay().getHeight();
      textView.setDropDownWidth(width);
      int auto_width=textView.getWidth();
      int offset=(auto_width-width)/2;
      Log.i("AutoCompleteTextViewActivity", "offset="+offset);
      textView.setDropDownHorizontalOffset(offset);
      textView.setOnDismissListener(dismissListener);
      
      LinearLayout linear=(LinearLayout)findViewById(R.id.linear);
      int linear_height=linear.getHeight();
      int auto_height=textView.getHeight();
      textView.setDropDownVerticalOffset((linear_height-auto_height)/2);
    }
    
	  static final String[] KEYWORDS = new String[] { "abc", "allen", "bird", "bike", "book", "cray",  
            "david", "demon", "eclipse", "felling", "frank", "google","above" ,"align","abstract",
            "abstraction","absorbent","abstention","absorption","aboutyouaremyangelhelloworld",
            "green", "hill", "hook","jin zhiwen", "jack", "jay", "king","kevin","kobe",  
            "lily", "lucy", "mike", "nike", "nail", "open","open cv",  
            "panda", "pp", "queue", "ray allen", "risk", "tim cook","T-MAC","tony allen",  
            "x man", "x phone", "yy", "world", "w3c", "zoom","zhu ziqing"};
	
	  public void onItemClick(AdapterView<?> parent, View view, int position,long id) {  		
        //String keyword = mList.get(position); 显示的内容和所选的内容不相符
        String keyword = (String) parent.getAdapter().getItem(position);
        Log.i("AutoCompleteTextViewActivity", keyword);
        textView.setText(keyword); 
        //locate the cursor	to end of the text
        textView.setSelection(textView.getText().length());
    } 	
}
/*
 在程序中输出日志, 使用 android.util.Log 类.
该类提供了若干静态方法

Log.v(String tag, String msg);
Log.d(String tag, String msg);
Log.i(String tag, String msg);
Log.w(String tag, String msg);
Log.e(String tag, String msg);

分别对应 Verbose, Debug, Info, Warning, Error.

tag是一个标识,可以是任意字符串,通常可以使用类名+方法名, 主要是用来在查看日志时提供一个筛选条件.

查看日志请使用
adb logcat
关于adb的更多信息请查看官方网站.
当执行 adb logcat 后会以tail方式实时显示出所有的日志信息.
这时候我们通常需要对信息进行过滤,来显示我们需要的信息, 这时候我们指定的 tag就派上了用场.
adb logcat -s AutoCompleteTextViewActivity:I
这时将只显示tag为AutoCompleteTextViewActivity,级别为I或级别高于I(Warning,Error)的日志信息.  
 * */

 

name_item.xml

<?xml version="1.0" encoding="utf-8"?>
    <CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/tv_name"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:textColor="#000000"  
        android:textSize="16sp"
        android:ellipsize="marquee"
        android:layout_weight="1"
        android:singleLine="true"
        android:textAlignment="inherit" 
        />     
    

        

 autocomplete.xml

<?xml version="1.0" encoding="utf-8"?>
<!-- 
 * Copyright (C) 2007 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 -->

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/linear"
    android:orientation="horizontal"
    android:layout_width="fill_parent" 
    android:layout_height="50dip"
    android:background="#2FB8CB"
    android:gravity="center"
    >
    <Button android:id="@+id/back" 
    android:layout_width="40dip"
    android:layout_height="40dip"
    android:text="&lt;" 
    android:textColor="#fff"
    android:textSize="30sp"
    android:background="#2FB8CB"
    android:layout_gravity="center"
    />
    
    <AutoCompleteTextView android:id="@+id/auto_complete"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"            
            android:singleLine="true"
            android:ems="10"            
            android:layout_gravity="center"
            android:textSize="20sp"
            android:completionThreshold="1"
            android:popupBackground="#fff"
            android:background="@drawable/search"
            android:textColor="#000"
            android:paddingLeft="8dip"
            android:paddingRight="8dip"
            />

<!--  xml中 android:ems属性 ,作为EditText 默认生成 的属性,其含义是需要编辑的 字符串长度 。
设置为10时,最多编辑 10个em ,一个em单位是 两个inch ,但是随着自动调整,在Android中 em代表‘M’的数量 。  

-->
    <ImageButton android:id="@+id/search" 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" 
    android:background="#2FB8CB"
    android:layout_gravity="center"
    android:src="@android:drawable/ic_menu_search"/>
</LinearLayout>

 

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.eoemobile.book.ex_widgetdemo"
      android:versionCode="1"
      android:versionName="1.0.0">
     <application android:icon="@drawable/icon" android:label="@string/app_name">
     <activity android:name=".AutoCompleteTextViewActivity"></activity>
     </application>
     <uses-sdk android:minSdkVersion="17" android:targetSdkVersion="19" />
</manifest> 

 

 

demo :



 

@drawable/search:



 

  • 大小: 54.3 KB
  • 大小: 3 KB
分享到:
评论

相关推荐

    AutoCompleteTextView

    ArrayAdapter&lt;String&gt; adapter = new ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, suggestions); AutoCompleteTextView autoCompleteTextView = findViewById(R.id.autocomplete_text_view); ...

    AutoCompleteTextView和自定义的CursorAdapter

    在Android开发中,`AutoCompleteTextView` 是一个非常实用的组件,它提供了自动补全功能,用户在输入时可以根据预设的数据集得到建议的匹配项。这篇文章将深入探讨`AutoCompleteTextView` 的工作原理以及如何结合...

    AutoCompleteTextView自动提示问题

    AutoCompleteTextView是Android SDK提供的一种UI组件,用于在用户输入时提供下拉列表的自动提示功能,极大地提升了用户的输入体验。这个控件通常用于搜索框、地址输入等场景,可以根据用户输入的部分字符快速匹配出...

    AutoCompleteTextView的简单使用

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

    AutoCompleteTextView自动完成文字输入

    AutoCompleteTextView是Android SDK提供的一种用于输入文本时自动补全的视图组件,它扩展了EditText,能够根据用户输入的部分文字动态显示出匹配的建议列表。这个功能在许多应用中非常常见,例如搜索引擎、地址...

    使用autoCompleteTextView读取历史记录

    ArrayAdapter&lt;String&gt; adapter = new ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, historyList); autoCompleteTextView.setAdapter(adapter); ``` 3. 读取历史记录: 读取历史记录通常涉及到...

    Android仿百度谷歌自动提示——AutoCompleteTextView

    本文将详细介绍如何在Android中仿照百度和谷歌的自动提示功能,利用`AutoCompleteTextView`控件来实现这一功能。 `AutoCompleteTextView`是Android SDK中的一个视图组件,它继承自`EditText`,增加了自动补全的功能...

    自定义AutoCompleteTextView下拉列表控件

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

    android中AutoCompleteTextView使用

    ArrayAdapter&lt;String&gt; adapter = new ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, items); autoCompleteTextView.setAdapter(adapter); ``` 其中,`items` 是包含建议项的字符串数组。 ### ...

    autocompleteTextview控件

    在Android开发中,`AutoCompleteTextView` 是一个非常实用的UI组件,它允许用户在输入文本时接收下拉建议,从而提升用户体验。这个控件基于`EditText`,但增加了自动补全的功能,常用于搜索框或者表单输入场景。本篇...

    AutoCompleteTextView 自动提示联系人信息

    ArrayAdapter&lt;Cursor&gt; adapter = new ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, cursor); autoCompleteTextView.setAdapter(adapter); ``` ### 提示联系人信息 在`AutoCompleteTextView`...

    TestCompleteText_AutoCompleteTextView和TextWatcher结合使用

    ArrayAdapter&lt;String&gt; adapter = new ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, dataSource); autoCompleteTextView.setAdapter(adapter); ``` 接下来,我们可以添加一个TextWatcher来监听...

    AutoCompleteTextView 显示更多

    标题与描述均提到了“AutoCompleteTextView 显示更多”,这主要关注于如何优化AutoCompleteTextView在Android应用中的表现,特别是如何调整下拉建议列表的高度,以便在屏幕上显示更多的选项。以下将深入探讨这一主题...

    Android自动文本填充AutoCompleteTextView

    ArrayAdapter&lt;String&gt; adapter = new ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, animalList); autoCompleteTextView = findViewById(R.id.auto_complete_text_view); autoCompleteTextView....

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

    AutoCompleteTextView是Android SDK提供的一种视图组件,用于在用户输入文本时提供下拉列表的自动补全功能。它能够极大地提升用户体验,特别是在用户需要从大量预定义选项中选择时。在开发移动应用,尤其是涉及搜索...

    AutoCompleteTextViewDemo

    AutoCompleteTextView是Android平台上一种非常实用的UI组件,主要用于实现自动补全或建议输入的功能。在给定的项目“AutoCompleteTextViewDemo”中,我们主要关注如何利用这个组件来展示历史记录,使得用户在输入时...

    AutoCompleteTextView从服务器上获得数据显示下拉列表

    AutoCompleteTextView是Android系统提供的一种可以自动补全的文本输入控件,它允许用户在输入时根据已有的数据集匹配并显示建议的选项。这个功能通常用于搜索框、地址输入等场景,提升用户体验。在本主题中,我们将...

    Android自定义AutoCompleteTextView

    在Android开发中,AutoCompleteTextView是一个非常常用的组件,它提供了自动补全的功能,适用于用户输入时需要提示相关信息的场景,比如搜索框、地址输入等。本文将深入探讨如何自定义AutoCompleteTextView,以满足...

Global site tag (gtag.js) - Google Analytics