随时随地阅读更多技术实战干货,获取项目源码、学习资料,请关注源代码社区公众号(ydmsq666)
在Android也可以实现点击网址、email等自动连接,在输入框中输入数据,在下面列表中列出所有匹配的数据,点击实现自动补全的功能,类似百度搜索框,代码如下:
Activity:
package com.lovo.activity;
import com.lovo.R;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
public class ContentActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 设置布局
setContentView(R.layout.content_main);
// 自动提示时匹配的数组源
String[] ary = new String[] { "lovo", "love", "logo", "android", "and" };
// 创建数组适配器。参数2:android内部提供的下拉列表样式
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_dropdown_item_1line, ary);
// 获得AutoCompleteTextView对象
AutoCompleteTextView autoText = (AutoCompleteTextView) findViewById(R.id.autoText);
// 将设配器加入到自动完成组件中
autoText.setAdapter(adapter);
}
}
布局:content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:autoLink="web"
android:text="网址:http://www.baidu.com" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:autoLink="email"
android:text="email:abc@sina.com" />
<!-- 如果使用autoLink="all"表示自动匹配所有 -->
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:autoLink="phone"
android:text="电话:13888888888" />
<AutoCompleteTextView
android:id="@+id/autoText"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
附上图片效果: