AutoCompleteTextView与MultiAutoCo
一、AutoCompleteTextView相关介绍
动态匹配输入的内容,如百度搜索引擎输入时可以根据内容显示匹配的热门信息。
二、AutoCompleteTextView相关属性描述
android:completionHint
设置出现在下拉菜单底部的提示信息
android:completionThreshold
设置触发补全提示信息的字符个数
android:dropDownHorizontalOffset
设置下拉菜单于文本框之间的水平偏移量
android:dropDownHeight
设置下拉菜单的高度
android:dropDownWidth
设置下拉菜单的宽度
android:singleLine
设置单行显示文本内容
android:dropDownVerticalOffset
设置下拉菜单于文本框之间的垂直偏移量
completionHint/setCompletionHint(CharSequence)
设置显示在下拉菜单中的提示内容
popupBackground/setDropDownBackgroundResource(int)
下拉菜单背景
三、AutoCompleteTextView相关DEMO
(一)Demo1效果如下
2630915-8141825da79902cb.gifxml
<AutoCompleteTextView
android:id="@+id/tv_search"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/hint_type"
android:completionHint="@string/chint_recent"
android:completionThreshold="1" />
MainActivity
private void initSearchView() {
mSearchTv = (AutoCompleteTextView) findViewById(R.id.tv_search);
String[] mSearchHistoryArray = getHistoryArray(SP_KEY_SEARCH);
mSearchAdapter = new ArrayAdapter<>(
this,
android.R.layout.simple_dropdown_item_1line,
mSearchHistoryArray
);
mSearchTv.setAdapter(mSearchAdapter); // 设置适配器
// 设置下拉提示框的高度为200dp
// mAutoCompleteTv.setDropDownHeight();
// 或XML中为android:dropDownHeight="200dp"
// 默认当输入2个字符以上才会提示, 现在当设置输入1个字符就自动提示
// 或XML中为android:completionThreshold="1"
// mAutoCompleteTv.setThreshold(1);
// 设置下拉提示框中底部的提示
// mAutoCompleteTv.setCompletionHint("最近的5条记录");
// 设置单行输入限制
// mAutoCompleteTv.setSingleLine(true);
}
private String[] getHistoryArray(String key) {
String[] array = getHistoryFromSharedPreferences(key).split(SP_SEPARATOR);
if (array.length > MAX_HISTORY_COUNT) { // 最多只提示最近的50条历史记录
String[] newArray = new String[MAX_HISTORY_COUNT];
System.arraycopy(array, 0, newArray, 0, MAX_HISTORY_COUNT); // 实现数组间的内容复制
}
return array;
}
保存AutoCompleteTextView中的历史记录数据逻辑(SharedPreferences中或者SQLite):
1) 获取搜索框文本信息。
2)判断搜索内容是否已存在于历史文件中,已存在则不再添加。
3)新的历史搜索添加完了更新Adapter。
(二)、DEMO2
效果如下
关键代码
自动补全的匹配模式的配置三种
MODE_CONTAINS / MODE_STARTSWITH(default) / MODE_SPLIT
支持使用@字符来预览所有提示内容
自定义adapter时候一定要实现Filterable接口,不然会报错
当你在MainActivity刷新数据的时候,必须得更新你的ArrayFilter中的数据,不然过滤器中的原始数据时不会更改的
public class AutoCompleteAdapter extends BaseAdapter implements Filterable {
private static final int MODE_NONE = 0x000; // 0000b
public static final int MODE_CONTAINS = 0x001; // 0001b
public static final int MODE_STARTSWITH = 0x002; // 0010b
public static final int MODE_SPLIT = 0x004; // 0100b
private static final String SPLIT_SEPARATOR = "[,.\\s]+"; // 分隔符,默认为空白符、英文逗号、英文句号
private static boolean isFound = false; // 当MODE_STARTSWITH模式匹配成功时,不再进行MODE_SPLIT模式的匹配
private int defaultMode = MODE_STARTSWITH; // 0110b
private LayoutInflater inflater;
private ArrayFilter mArrayFilter;
private ArrayList<String> mOriginalValues; // 所有的item
private List<String> mObjects; // 过滤后的item
private final Object mLock = new Object(); // 同步锁
private int maxMatch = 10; // 最多显示的item数目,负数表示全部
private int simpleItemHeight; // 单行item的高度值,故需要在XML中固定父布局的高度值
private char previewChar = '@'; // 默认字符
private boolean isSupportPreview = false; // 是否可以使用@符号进行预览全部提示内容
public AutoCompleteAdapter(Context context, ArrayList<String> mOriginalValues) {
this(context, mOriginalValues, -1);
}
public AutoCompleteAdapter(Context context, ArrayList<String> mOriginalValues, int maxMatch) {
this.mOriginalValues = mOriginalValues;
// 初始化时将其设置成mOriginalValues,避免在未进行数据保存时执行删除操作导致程序的崩溃
this.mObjects = mOriginalValues;
this.maxMatch = maxMatch;
inflater = LayoutInflater.from(context);
initViewHeight();
}
private void initViewHeight() {
View view = inflater.inflate(R.layout.simple_dropdown_item_1line, null);
LinearLayout linearLayout = (LinearLayout) view.findViewById(R.id.layout_item);
linearLayout.measure(0, 0);
// 其他方法获取的高度值会因View尚未被绘制而获取到0
simpleItemHeight = linearLayout.getMeasuredHeight();
}
public int getSimpleItemHeight() {
return simpleItemHeight; // 5 * 2 + 28(dp) => 103(px)
}
public void setSupportPreview(boolean isSupportPreview){
this.isSupportPreview = isSupportPreview;
}
public void setSupportPreview(boolean isSupportPreview, char previewChar){
this.isSupportPreview = isSupportPreview;
this.previewChar = previewChar;
}
@Override
public int getCount() {
return mObjects.size();
}
@Override
public Object getItem(int position) {
return mObjects.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.simple_dropdown_item_1line, null);
holder.tv = (TextView) convertView.findViewById(R.id.tv_simple_item);
holder.iv = (ImageView) convertView.findViewById(R.id.iv_simple_item);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tv.setText(mObjects.get(position));
holder.iv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String value = mObjects.remove(position);
if (mDeleteListener != null) {
mDeleteListener.onSimpleItemDeletedListener(value);
}
if (mFilterListener != null) {
mFilterListener.onFilterResultsListener(mObjects.size());
}
mOriginalValues.remove(value);
notifyDataSetChanged();
}
});
return convertView;
}
private static class ViewHolder {
TextView tv;
ImageView iv;
}
public void setDefaultMode(int defaultMode) {
this.defaultMode = defaultMode;
}
public void add(String item) {
mOriginalValues.add(item);
notifyDataSetChanged(); //
}
public void clear() {
if(mOriginalValues != null && !mOriginalValues.isEmpty()) {
mOriginalValues.clear();
notifyDataSetChanged(); //
}
}
// Interface
public interface OnSimpleItemDeletedListener {
void onSimpleItemDeletedListener(String value);
}
private OnSimpleItemDeletedListener mDeleteListener;
public void setOnSimpleItemDeletedListener(OnSimpleItemDeletedListener listener) {
this.mDeleteListener = listener;
}
// Interface
public interface OnFilterResultsListener {
void onFilterResultsListener(int count);
}
private OnFilterResultsListener mFilterListener;
public void setOnFilterResultsListener(OnFilterResultsListener listener) {
this.mFilterListener = listener;
}
@Override
public Filter getFilter() {
if (mArrayFilter == null) {
mArrayFilter = new ArrayFilter(mFilterListener);
}
return mArrayFilter;
}
private class ArrayFilter extends Filter {
private OnFilterResultsListener listener;
public ArrayFilter(OnFilterResultsListener listener) {
this.listener = listener;
}
@Override
protected FilterResults performFiltering(CharSequence prefix) {
FilterResults results = new FilterResults();
if (mOriginalValues == null) {
synchronized (mLock) {
mOriginalValues = new ArrayList<>(mObjects);
}
}
if (prefix == null || prefix.length() == 0) {
synchronized (mLock) {
ArrayList<String> list = new ArrayList<>(mOriginalValues);
results.values = list;
results.count = list.size();
}
} else {
if (isSupportPreview) {
int index = prefix.toString().indexOf(String.valueOf(previewChar));
if (index != -1) {
prefix = prefix.toString().substring(index + 1);
}
}
String prefixString = prefix.toString().toLowerCase(); // prefixString
final int count = mOriginalValues.size(); // count
final ArrayList<String> newValues = new ArrayList<>(count); // newValues
for (int i = 0; i < count; i++) {
final String value = mOriginalValues.get(i); // value
final String valueText = value.toLowerCase(); // valueText
// 1. 匹配所有
if ((defaultMode & MODE_CONTAINS) != MODE_NONE) {
if (valueText.contains(prefixString)) {
newValues.add(value);
}
} else { // support: defaultMode = MODE_STARTSWITH | MODE_SPLIT
// 2. 匹配开头
if ((defaultMode & MODE_STARTSWITH) != MODE_NONE) {
if (valueText.startsWith(prefixString)) {
newValues.add(value);
isFound = true;
}
}
// 3. 分隔符匹配,效率低
if (!isFound && (defaultMode & MODE_SPLIT) != MODE_NONE) {
final String[] words = valueText.split(SPLIT_SEPARATOR);
for (String word : words) {
if (word.startsWith(prefixString)) {
newValues.add(value);
break;
}
}
}
if(isFound) { // 若在MODE_STARTSWITH模式中匹配,则再次复位进行下一次判断
isFound = false;
}
}
if (maxMatch > 0) { // 限制显示item的数目
if (newValues.size() > maxMatch - 1) {
break;
}
}
} // for (int i = 0; i < count; i++)
results.values = newValues;
results.count = newValues.size();
}
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
//noinspection unchecked
mObjects = (List<String>) results.values;
if (results.count > 0) {
// 由于当删除提示框中的记录行时,而AutoCompleteTextView此时内容又不改变,故不会触发FilterResults事件
// 导致删除记录行时,提示框的高度不会发生相应的改变
// 解决方法:需要在ImageView的点击监听器中也调用OnFilterResultsListener.onFilterResultsListener()
// 来共同完成
if (listener != null) {
listener.onFilterResultsListener(results.count);
}
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
}
}
刷新方法
/**
* 刷新数据
* @param reLists
*/
public void refresh(List<String> reLists) {
if (mLists != null) {
mLists.clear();
}
if (mUnfilteredData != null) {
mUnfilteredData.clear();
}
mLists.addAll(reLists);
mUnfilteredData.addAll(reLists);
}
(三)、Demo3
<ProgressBar
android:id="@+id/login_progress"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:visibility="gone"/>
<ScrollView
android:id="@+id/login_form"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="@+id/email_login_form"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<AutoCompleteTextView
android:id="@+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/prompt_email"
android:inputType="textEmailAddress"
android:maxLines="1"
android:singleLine="true"/>
<!-android:inputType="textEmailAddress" 说明软件盘中会有@符号 -->
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/prompt_password"
android:imeActionId="@+id/login"
android:imeActionLabel="@string/action_sign_in_short"
android:imeOptions="actionUnspecified"
android:inputType="textPassword"
android:maxLines="1"
android:singleLine="true"/>
</android.support.design.widget.TextInputLayout>
<Button
android:id="@+id/email_sign_in_button"
style="?android:textAppearanceSmall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="@string/action_sign_in"
android:textStyle="bold"/>
</LinearLayout>
</ScrollView>
TextInputLayout是一个显示在EditText上方的浮动标签。跟ScrollView一样,TextInputLayout只接受一个子元素。
处理错误:TextInputLayout可以处理错误,我们先检查输入的信息是否正常,如果不符合我们的要求我们可以设置错误XXX.setError();
样式:TextInputLayout,所有色彩展示都是在style.xml中设置
/**
* A login screen that offers login via email/password.
*/
public class LoginActivity extends AppCompatActivity implements LoaderCallbacks<Cursor> {
/**
* Id to identity READ_CONTACTS permission request.
*/
private static final int REQUEST_READ_CONTACTS = 0;
/**
* A dummy authentication store containing known user names and passwords.
* TODO: remove after connecting to a real authentication system.
*/
private static final String[] DUMMY_CREDENTIALS = new String[]{
"foo@example.com:hello", "bar@example.com:world"
};
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
private UserLoginTask mAuthTask = null;
// UI references.
private AutoCompleteTextView mEmailView;
private EditText mPasswordView;
private View mProgressView;
private View mLoginFormView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// Set up the login form.
mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
populateAutoComplete();
mPasswordView = (EditText) findViewById(R.id.password);
mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
if (id == R.id.login || id == EditorInfo.IME_NULL) {
attemptLogin();
return true;
}
return false;
}
});
Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
mEmailSignInButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
attemptLogin();
}
});
mLoginFormView = findViewById(R.id.login_form);
mProgressView = findViewById(R.id.login_progress);
}
private void populateAutoComplete() {
if (!mayRequestContacts()) {
return;
}
getLoaderManager().initLoader(0, null, this);
}
private boolean mayRequestContacts() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return true;
}
if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
return true;
}
if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
Snackbar.make(mEmailView, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE)
.setAction(android.R.string.ok, new View.OnClickListener() {
@Override
@TargetApi(Build.VERSION_CODES.M)
public void onClick(View v) {
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
}
});
} else {
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
}
return false;
}
/**
* Callback received when a permissions request has been completed.
*/
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
if (requestCode == REQUEST_READ_CONTACTS) {
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
populateAutoComplete();
}
}
}
/**
* Attempts to sign in or register the account specified by the login form.
* If there are form errors (invalid email, missing fields, etc.), the
* errors are presented and no actual login attempt is made.
*/
private void attemptLogin() {
if (mAuthTask != null) {
return;
}
// Reset errors.
mEmailView.setError(null);
mPasswordView.setError(null);
// Store values at the time of the login attempt.
String email = mEmailView.getText().toString();
String password = mPasswordView.getText().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid password, if the user entered one.
if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
mPasswordView.setError(getString(R.string.error_invalid_password));
focusView = mPasswordView;
cancel = true;
}
// Check for a valid email address.
if (TextUtils.isEmpty(email)) {
mEmailView.setError(getString(R.string.error_field_required));
focusView = mEmailView;
cancel = true;
} else if (!isEmailValid(email)) {
mEmailView.setError(getString(R.string.error_invalid_email));
focusView = mEmailView;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else {
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
showProgress(true);
mAuthTask = new UserLoginTask(email, password);
mAuthTask.execute((Void) null);
}
}
private boolean isEmailValid(String email) {
//TODO: Replace this with your own logic
return email.contains("@");
}
private boolean isPasswordValid(String password) {
//TODO: Replace this with your own logic
return password.length() > 4;
}
/**
* Shows the progress UI and hides the login form.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show) {
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
mLoginFormView.animate().setDuration(shortAnimTime).alpha(
show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
});
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mProgressView.animate().setDuration(shortAnimTime).alpha(
show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
} else {
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
@Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
return new CursorLoader(this,
// Retrieve data rows for the device user's 'profile' contact.
Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,
// Select only email addresses.
ContactsContract.Contacts.Data.MIMETYPE +
" = ?", new String[]{ContactsContract.CommonDataKinds.Email
.CONTENT_ITEM_TYPE},
// Show primary email addresses first. Note that there won't be
// a primary email address if the user hasn't specified one.
ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
}
@Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
List<String> emails = new ArrayList<>();
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
emails.add(cursor.getString(ProfileQuery.ADDRESS));
cursor.moveToNext();
}
addEmailsToAutoComplete(emails);
}
@Override
public void onLoaderReset(Loader<Cursor> cursorLoader) {
}
private void addEmailsToAutoComplete(List<String> emailAddressCollection) {
//Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
ArrayAdapter<String> adapter =
new ArrayAdapter<>(LoginActivity.this,
android.R.layout.simple_dropdown_item_1line, emailAddressCollection);
mEmailView.setAdapter(adapter);
}
private interface ProfileQuery {
String[] PROJECTION = {
ContactsContract.CommonDataKinds.Email.ADDRESS,
ContactsContract.CommonDataKinds.Email.IS_PRIMARY,
};
int ADDRESS = 0;
int IS_PRIMARY = 1;
}
/**
* Represents an asynchronous login/registration task used to authenticate
* the user.
*/
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
private final String mEmail;
private final String mPassword;
UserLoginTask(String email, String password) {
mEmail = email;
mPassword = password;
}
@Override
protected Boolean doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
try {
// Simulate network access.
Thread.sleep(2000);
} catch (InterruptedException e) {
return false;
}
for (String credential : DUMMY_CREDENTIALS) {
String[] pieces = credential.split(":");
if (pieces[0].equals(mEmail)) {
// Account exists, return true if the password matches.
return pieces[1].equals(mPassword);
}
}
// TODO: register the new account here.
return true;
}
@Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
finish();
} else {
mPasswordView.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
}
}
@Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
}
isEmailValid(String email) ——是否是email地址的标准
isPasswordValid(String password) ——是否符合密码标准
四、MultiAutoCompleteTextView
功能:可支持选择多个值(在多次输入的情况下),分别用分隔符分开,并且在每个值选中的时候再次输入值时会自动去匹配,可用在发短信,发邮件时选择联系人这种类型。
//初始化控件
private MultiAutoCompleteTextView macTextView;
macTextView=(MultiAutoCompleteTextView)findViewById(R.id.multiAutoCompleteTextView);
//将adapter与当前MultiAutoCompleteTextView绑定
macTextView.setAdapter(adapter);
//设置以逗号为分隔符
macTextView.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
<MultiAutoCompleteTextView
android:id="@+id/mauto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:completionThreshold="1"/>