如何为 AutoCompleteTextView 创建自定义 BaseAdapter [英] How to create custom BaseAdapter for AutoCompleteTextView

查看:34
本文介绍了如何为 AutoCompleteTextView 创建自定义 BaseAdapter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在为 AutoCompleteTextView 创建自定义 ArrayAdapter 遇到困难,尽管在互联网上找到了以下代码,但仍会出现此类错误:

  • 不会出现下拉菜单.
  • 不会显示自定义对象及其详细信息.

所以对于那些与我有或有同样问题的人,我建议使用 BaseAdapter 代替 AutoCompleteTextView.

解决方案

以下是我使用 ArrayAdapter 的工作代码.

假设来自 Web 服务的响应数据如下所示:

<预><代码>[{"id": "1","name": "信息技术"},{"id": "2","name": "人力资源"},{"id": "3","name": "营销和公关"},{"id": "4","name": "研究与开发"}]

<小时>

然后在您的 Android 客户端中:

部门类:

公开课系{公共整数 ID;公共字符串名称;}

自定义适配器类:

public class DepartmentArrayAdapter extends ArrayAdapter{私有最终上下文 mContext;私人最终名单<部门>m部门;私人最终名单<部门>mDepartmentsAll;私有最终 int mLayoutResourceId;公共部门阵列适配器(上下文上下文,整数资源,列表<部门>部门){超级(上下文,资源,部门);this.mContext = 上下文;this.mLayoutResourceId = 资源;this.mDepartments = new ArrayList<>(部门);this.mDepartmentsAll = new ArrayList<>(部门);}公共 int getCount() {返回 mDepartments.size();}公共部门getItem(int position){返回 mDepartments.get(position);}public long getItemId(int position) {返回位置;}@覆盖public View getView(int position, View convertView, ViewGroup parent) {尝试 {if (convertView == null) {LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();convertView = inflater.inflate(mLayoutResourceId, parent, false);}部门部门 = getItem(position);TextView 名称 = (TextView) convertView.findViewById(R.id.textView);name.setText(部门名称);} 捕获(异常 e){e.printStackTrace();}返回转换视图;}@覆盖公共过滤器 getFilter() {返回新过滤器(){@覆盖公共字符串 convertResultToString(Object resultValue) {return ((部门) resultValue).name;}@覆盖受保护的 FilterResults performFiltering(CharSequence 约束){FilterResults filterResults = new FilterResults();列表<部门>部门建议 = 新的 ArrayList<>();如果(约束!= null){对于(部门部门:mDepartmentsAll){if (department.name.toLowerCase().startsWith(constraint.toString().toLowerCase())) {部门建议.添加(部门);}}filterResults.values = 部门建议;filterResults.count = 部门建议.size();}返回过滤器结果;}@覆盖protected void publishResults(CharSequence 约束,FilterResults 结果) {mDepartments.clear();如果(结果!= null && results.count > 0){//使用 mDepartments.addAll((ArrayList) results.values) 时避免未经检查的强制转换警告;for (Object object : (List) results.values) {如果(对象实例部门){mDepartments.add((部门)对象);}}notifyDataSetChanged();} else if(约束== null){//无过滤器,重新添加整个原始列表mDepartments.addAll(mDepartmentsAll);notifyDataSetInvalidated();}}};}}

主要活动:

@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mAutoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);mAutoCompleteTextView.setThreshold(1);新部门请求().execute();}私有类 DepartmentRequest 扩展了 AsyncTask{@覆盖受保护的 JSONArray doInBackground(Void... voids) {OkHttpJsonArrayRequest request = new OkHttpJsonArrayRequest();尝试 {return request.get("http://...");} catch (IOException | JSONException e) {e.printStackTrace();}返回空;}@覆盖受保护的无效 onPostExecute(JSONArray jsonArray) {super.onPostExecute(jsonArray);如果 (jsonArray != null && jsonArray.length() > 0) {Gson gson = new Gson();部门[] 部门= gson.fromJson(jsonArray.toString(), 部门[].class);mDepartmentList = Arrays.asList(departments);mDepartmentArrayAdapter = new DepartmentArrayAdapter(mContext, R.layout.simple_text_view, mDepartmentList);mAutoCompleteTextView.setAdapter(mDepartmentArrayAdapter);}}}私有类 OkHttpJsonArrayRequest {OkHttpClient 客户端 = new OkHttpClient();//HTTP 获取请求JSONArray get(String url) 抛出 IOException, JSONException {请求请求 = new Request.Builder().url(网址).建造();响应 response = client.newCall(request).execute();返回新的 JSONArray(response.body().string());}}

截图如下:

希望这有帮助!

I've been having difficulty creating a custom ArrayAdapter for AutoCompleteTextView such errors that would come up despite following code found on the internet would be:

  • Dropdown would not appear.
  • Custom Objects and their details would not appear.

So for those who are having or had the same problem as me, I recommend using BaseAdapter for AutoCompleteTextView instead.

解决方案

The following is my working code using ArrayAdapter.

Let's assume the reponse data from web service looks like the following:

[
    {
        "id": "1",
        "name": "Information Technology"
    },
    {
        "id": "2",
        "name": "Human Resources"
    },
    {
        "id": "3",
        "name": "Marketing and PR"
    },
    {
        "id": "4",
        "name": "Research and Developement"
    }
]


Then in your Android client:

Department class:

public class Department {
    public int id;
    public String name;
}

Custom Adapter class:

public class DepartmentArrayAdapter extends ArrayAdapter<Department> {
    private final Context mContext;
    private final List<Department> mDepartments;
    private final List<Department> mDepartmentsAll;
    private final int mLayoutResourceId;

    public DepartmentArrayAdapter(Context context, int resource, List<Department> departments) {
        super(context, resource, departments);
        this.mContext = context;
        this.mLayoutResourceId = resource;
        this.mDepartments = new ArrayList<>(departments);
        this.mDepartmentsAll = new ArrayList<>(departments);
    }

    public int getCount() {
        return mDepartments.size();
    }

    public Department getItem(int position) {
        return mDepartments.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        try {
            if (convertView == null) {                    
                LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
                convertView = inflater.inflate(mLayoutResourceId, parent, false);
            }
            Department department = getItem(position);
            TextView name = (TextView) convertView.findViewById(R.id.textView);
            name.setText(department.name);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return convertView;
    }

    @Override
    public Filter getFilter() {
        return new Filter() {
            @Override
            public String convertResultToString(Object resultValue) {
                return ((Department) resultValue).name;
            }

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                FilterResults filterResults = new FilterResults();
                List<Department> departmentsSuggestion = new ArrayList<>();
                if (constraint != null) {
                    for (Department department : mDepartmentsAll) {
                        if (department.name.toLowerCase().startsWith(constraint.toString().toLowerCase())) {
                            departmentsSuggestion.add(department);
                        }
                    }
                    filterResults.values = departmentsSuggestion;
                    filterResults.count = departmentsSuggestion.size();
                }
                return filterResults;
            }

            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                mDepartments.clear();
                if (results != null && results.count > 0) {
                    // avoids unchecked cast warning when using mDepartments.addAll((ArrayList<Department>) results.values);
                    for (Object object : (List<?>) results.values) {
                        if (object instanceof Department) {
                            mDepartments.add((Department) object);
                        }
                    }
                    notifyDataSetChanged();
                } else if (constraint == null) {
                    // no filter, add entire original list back in
                    mDepartments.addAll(mDepartmentsAll);
                    notifyDataSetInvalidated();
                }
            }
        };
    }
}

Main Activity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mAutoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
    mAutoCompleteTextView.setThreshold(1);

    new DepartmentRequest().execute();
}

private class DepartmentRequest extends AsyncTask<Void, Void, JSONArray> {
        @Override
        protected JSONArray doInBackground(Void... voids) {
            OkHttpJsonArrayRequest request = new OkHttpJsonArrayRequest();
            try {
                return request.get("http://...");
            } catch (IOException | JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(JSONArray jsonArray) {
            super.onPostExecute(jsonArray);
            if (jsonArray != null && jsonArray.length() > 0) {
                Gson gson = new Gson();
                Department[] departments = gson.fromJson(jsonArray.toString(), Department[].class);
                mDepartmentList = Arrays.asList(departments);
                mDepartmentArrayAdapter = new DepartmentArrayAdapter(mContext, R.layout.simple_text_view, mDepartmentList);
                mAutoCompleteTextView.setAdapter(mDepartmentArrayAdapter);
            }
        }
    }

    private class OkHttpJsonArrayRequest {
        OkHttpClient client = new OkHttpClient();
        // HTTP GET REQUEST
        JSONArray get(String url) throws IOException, JSONException {
            Request request = new Request.Builder()
                    .url(url)
                    .build();
            Response response = client.newCall(request).execute();
            return new JSONArray(response.body().string());
        }
    }

Here's the screenshot:

Hope this helps!

这篇关于如何为 AutoCompleteTextView 创建自定义 BaseAdapter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆