Android 6.0.1中自定义AutoCompleteTextView失效,旧版本正常需改代码吗?
Absolutely—Android 6.0 (API 23) brought several under-the-hood behavior changes that can break custom AutoCompleteTextView implementations that worked flawlessly on older versions. Let’s walk through the most common issues and how to fix them:
1. 过滤逻辑必须异步执行
API 23+ enforces that the filtering work in performFiltering() runs on a background thread. If your old code did filtering on the main thread, the dropdown won’t show up at all.
Fix this by ensuring your custom Filter subclass strictly separates background work and UI updates:
@Override protected FilterResults performFiltering(CharSequence constraint) { FilterResults results = new FilterResults(); // 所有数据过滤逻辑都在这里完成,绝对不能操作UI List<YourDataModel> filteredItems = yourCustomFilterLogic(constraint.toString()); results.values = filteredItems; results.count = filteredItems.size(); return results; } @Override protected void publishResults(CharSequence constraint, FilterResults results) { // 这里只做UI更新,系统会自动保证在主线程执行 if (results.count > 0) { clear(); addAll((List<YourDataModel>) results.values); notifyDataSetChanged(); } else { notifyDataSetInvalidated(); } }
2. 调整下拉弹窗的窗口类型
API 23 tightened restrictions on window types for popups. If you customized the dropdown window type (e.g., using TYPE_SYSTEM_ALERT), it might get blocked by the system now.
Use a window type that’s compatible with app-level UI:
// 替换旧的弹窗类型设置 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { getDropDownPopup().setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL); } // 针对API 26+,可以改用这个 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { getDropDownPopup().setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY); }
3. 修正过滤触发条件
The enoughToFilter() method’s default behavior changed slightly in API 23. If your custom logic wasn’t explicit about when to trigger filtering, the dropdown might not appear when expected.
Override it to define clear trigger rules:
@Override public boolean enoughToFilter() { CharSequence inputText = getText(); // 根据你的需求设置最小输入长度,比如1个字符就触发 return inputText != null && inputText.length() >= 1; }
4. 适配AppCompat主题与控件
If you’re using the support library or AndroidX, make sure your custom AutoCompleteTextView extends the AppCompat variant instead of the framework one. API 23+ relies more heavily on AppCompat’s styling and behavior fixes.
Change your class inheritance:
// 替换成AppCompat版本 public class CustomAutoCompleteTextView extends androidx.appcompat.widget.AutoCompleteTextView { // ... 你的自定义逻辑 }
5. 检查运行时权限
If your filtering logic relies on data that requires runtime permissions (e.g., contacts, external storage), API 23+ blocks access until the user grants permission. If you haven’t added permission request code, your filter might return empty results, making it seem like the dropdown isn’t working.
Add runtime permission checks before loading data for filtering.
内容的提问来源于stack exchange,提问作者shamjins

