TextView的升级版———AutoCompleteTextView
AutoCompleteTextView顾名知义,可以自动提示的TextView,还可以提示错误信息。
这里介绍基本的使用,能够满足绝大部分需求
- 效果图
XML布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".MainActivity">
<AutoCompleteTextView
android:id="@+id/actv_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="用户名" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="error"
android:text="提示错误" />
</LinearLayout>
测试类
package com.example.kongqw.autocompletetextviewdemo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
public class MainActivity extends AppCompatActivity {
private AutoCompleteTextView mAutoCompleteTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAutoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.actv_username);
String[] emailAddressCollection = {"kongqw@foxmail.com", "qq4878802", "123@qq.com", "123456789", "123888888"};
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, emailAddressCollection);
mAutoCompleteTextView.setAdapter(adapter);
}
// 提示错误
public void error(View view){
mAutoCompleteTextView.setError("这里是错误提示");
}
}
自动提示
核心方法就是AutoCompleteTextView的setAdapter()
这里模拟了几个已经记住的字符串,实际应用当中,这些数据可以读数据或者怎样,根据实际情况
mAutoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.actv_username);
String[] emailAddressCollection = {"kongqw@foxmail.com", "qq4878802", "123@qq.com", "123456789", "123888888"};
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, emailAddressCollection);
mAutoCompleteTextView.setAdapter(adapter);
显示错误信息
mAutoCompleteTextView.setError("这里是错误提示");
修改下划线颜色
修改res->values->styles.xml下”AppTheme”里的colorAccent属性
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
……
<item name="colorAccent">#00DD00</item>
</style>
- 效果(#00DD00)
补充
AutoCompleteTextView可以和TextInputLayout结合使用,效果还是不错的
TextInputLayout文章:http://blog.csdn.net/q4878802/article/details/49780691
- 效果图
AutoCompleteTextView还有好多方法,刚兴趣的自行研究下把