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="<" 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: