【问题标题】:How to create custom BaseAdapter for AutoCompleteTextView如何为 AutoCompleteTextView 创建自定义 BaseAdapter
【发布时间】:2016-01-07 22:15:03
【问题描述】:

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

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

所以对于那些和我有同样问题的人,我建议使用 BaseAdapter 来代替 AutoCompleteTextView。

【问题讨论】:

  • 您是如何从 Web 服务获取数据的?通过 httpurlconnection 或 okhttp 或 volley ...?其中一些是异步的。
  • 我使用 OkHttp。我创建了一个处理程序和一个可运行的,处理程序是从 Looper.getMainLooper(); 创建的。我在 Activity 的 onCreate() 中启动它。

标签: android android-arrayadapter baseadapter autocompletetextview


【解决方案1】:

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

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

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

然后在您的 Android 客户端中:

部门类:

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

自定义适配器类:

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();
                }
            }
        };
    }
}

主要活动:

@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());
        }
    }

截图如下:

希望这会有所帮助!

【讨论】:

  • @BNK,试图在 multiAutoCompleteTextView 中实现这一点。在您的示例中,有四个部门。如果用户键入的部门不是这四个部门怎么办?我们可以阻止用户进入这四个以外的部门吗?
  • @mr_tkp 如果用户键入的部门不是这四个部门,则不会显示任何内容
  • 2 小时寻找一个好例子。它是完整且独特的,对我有用。谢谢!
  • 一个完整的答案。在第一次运行时就像一个魅力。 Khudos @BNK
  • 你好@BNK你是一个真正的救星,如果堆栈溢出允许声誉转移我肯定会这样做
【解决方案2】:

自定义 BaseAdapter 类

public class ObjectAdapter extends BaseAdapter implements Filterable {

    private Context context;
    private ArrayList<Object> originalList;
    private ArrayList<Object> suggestions = new ArrayList<>();
    private Filter filter = new CustomFilter();

    /**
     * @param context      Context
     * @param originalList Original list used to compare in constraints.
     */
    public ObjectAdapter(Context context, ArrayList<Object> originalList) {
        this.context = context;
        this.originalList = originalList;
    }

    @Override
    public int getCount() {
        return suggestions.size(); // Return the size of the suggestions list.
    }

    @Override
    public Object getItem(int position) {
        return suggestions.get(position).getCountryName();
    }


    @Override
    public long getItemId(int position) {
        return 0;
    }

    /**
     * This is where you inflate the layout and also where you set what you want to display.
     * Here we also implement a View Holder in order to recycle the views.
     */
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = LayoutInflater.from(context);

        ViewHolder holder;

        if (convertView == null) {
            convertView = inflater.inflate(R.layout.adapter_autotext,
                    parent,
                    false);
            holder = new ViewHolder();
            holder.autoText = (TextView) convertView.findViewById(R.id.autoText);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.autoText.setText(suggestions.get(position).getCountryName());

        return convertView;
    }


    @Override
    public Filter getFilter() {
        return filter;
    }

    private static class ViewHolder {
        TextView autoText;
    }

    /**
     * Our Custom Filter Class.
     */
    private class CustomFilter extends Filter {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            suggestions.clear();

            if (originalList != null && constraint != null) { // Check if the Original List and Constraint aren't null.
                for (int i = 0; i < originalList.size(); i++) {
                    if (originalList.get(i).getCountryName().toLowerCase().contains(constraint)) { // Compare item in original list if it contains constraints.
                        suggestions.add(originalList.get(i)); // If TRUE add item in Suggestions.
                    }
                }
            }
            FilterResults results = new FilterResults(); // Create new Filter Results and return this to publishResults;
            results.values = suggestions;
            results.count = suggestions.size();

            return results;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            if (results.count > 0) {
                notifyDataSetChanged();
            } else {
                notifyDataSetInvalidated();
            }
        }
    }
}

主要活动类

public class MainActivity extends AppCompatActivity{

    private SGetCountryListAdapter countryAdapter;
    private ArrayList<SGetCountryList> countryList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        country = (AutoCompleteTextView) findViewById(R.id.country);
        countryAdapter = new SGetCountryListAdapter(getApplicationContext(),
                    ConnectionParser.SGetCountryList);

        country.setAdapter(countryAdapter);
        country.setThreshold(1);

    }

}

下拉布局

<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:id="@+id/autoText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="8dp"
        android:textColor="@color/black" />

</LinearLayout>

我的原始列表有来自网络服务的数据,所以我们假设它已经有数据。当然,您可以通过添加更多视图来自定义下拉菜单,只是不要忘记更新适配器以合并新视图。

【讨论】:

  • 好答案。但它不会从 DD 中选择项目并设置为 AutoCompleteTextView。你能提供解决方案吗?
  • 是的,我无法从下拉列表中选择任何 1 找到解决方案?
  • 但是我找到了另一种方法,我维护了# holder.autoText.SetOnClick,然后对其应用逻辑,它可以完美运行
  • 您从哪里获得 SGetCountryListAdapter?
  • 我在这里唯一要补充的是 getItem(int position) 不应返回 null。相反,您应该返回Suggestions.get(position).getCountryName() - 当您单击列表中的项目时,这将是您希望在AutoCompleteTextView 中看到的填充值。
猜你喜欢
  • 1970-01-01
  • 2012-02-20
  • 2012-05-10
  • 2011-11-13
  • 2013-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多