Android开发之自动完成

AutoComplete是属于比较常见的控件之一,在WEB开发中我们使用Ajax来实现自动完成。

在Android中,它自带了AutoCompleteTextView控件,通过它可以很容易的实现自动完成。

使用AutoCompleteTextView的步骤:

1.在布局文件中声明一个AutoCompleteTextView

 

<AutoCompleteTextView 
    	android:id="@+id/autocompleteTextview"
    	android:layout_width="fill_parent"
    	android:layout_height="wrap_content"
    />

 

 

 

2.定义提示条目的样式

 

<?xml version="1.0" encoding="utf-8"?>
<TextView 
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:id="@+id/autocompleteItem"
	android:layout_width="fill_parent"
	android:layout_height="fill_parent"
	android:padding="5dip"
	android:textColor="#0000FF"
/>

 

 

 

3.为AutoCompleteTextView提供一个ArrayAdapter

 

下面是完整的代码:

布局文件autocomplete.xml:

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="horizontal"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
    <TextView 
    	android:layout_width="wrap_content"
    	android:layout_height="wrap_content"
    	android:text="选择国家:"
    />
    <AutoCompleteTextView 
    	android:id="@+id/autocompleteTextview"
    	android:layout_width="fill_parent"
    	android:layout_height="wrap_content"
    />
</LinearLayout>


布局文件autocomplete_item.xml:

 

 

<?xml version="1.0" encoding="utf-8"?>
<TextView 
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:id="@+id/autocompleteItem"
	android:layout_width="fill_parent"
	android:layout_height="fill_parent"
	android:padding="5dip"
	android:textColor="#0000FF"
/>


Activity:

 

 

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;

import com.and.test.R;

public class AutoCompleteActivity extends Activity {
	private AutoCompleteTextView autoCompleteTextView = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.autocomplete);
		
		autoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.autocompleteTextview);
		List<String> countries = new ArrayList<String>();
		countries.add("America");
		countries.add("Ariabic");
		countries.add("China");
		countries.add("French");
		countries.add("Finish");
		countries.add("Finipino");
		countries.add("中文测试1");
		countries.add("中文测试2");
		
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.autocomplete_item,countries);
		autoCompleteTextView.setAdapter(adapter);
	}

}


显示的效果:

 

中文也是可以的:

至少要输入2个字符才会有提示。

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值