简体   繁体   English

如何为AutoCompleteTextView实现HashMap

[英]How to implement HashMap for AutoCompleteTextView

Good day, 美好的一天,

I have a following problem. 我有以下问题。 In my Android application I have a list of entries in XML that contains bus stop name and ID. 在我的Android应用程序中,我有一个XML条目列表,其中包含公交车站的名称和ID。 Those are put in a HashMap as IDs are unique, while stop names are not. 这些ID放在HashMap因为ID是唯一的,而站点名称则不是。 The user interface of activity contains an AutoCompleteTextView and Spinner. 活动的用户界面包含一个AutoCompleteTextView和Spinner。

My objective is to populate auto-complete view with stop names and then pass the ID of selected stop to the other class that will display bus lines on that stop in spinner (via remote API). 我的目标是使用停靠点名称填充自动完成视图,然后将所选停靠点的ID传递给另一个类,该类将在微调器中显示该停靠点的总线(通过远程API)。

So what the user will do is start typing stop name (eg Awesome Stop) and he will see two entries in auto-complete suggestions. 因此,用户将要做的就是开始输入停止名称(例如Awesome Stop),他将在自动完成建议中看到两个条目。 Depending on which one he will select spinner will show different results. 根据他选择微调器的方式,将显示不同的结果。

My problem is that I can't figure out how to couple AutoCompleteTextView and HashMap. 我的问题是我不知道如何结合使用AutoCompleteTextView和HashMap。 Auto-complete works well with ArrayAdapter<String> populated via ArrayList<String> but it's not terribly helpful because I can only get stop name back, and it's not very helpful since I actually need ID. 自动完成功能可以很好地与通过ArrayList<String> ArrayAdapter<String>填充的ArrayAdapter<String>使用,但是它并不是很有用,因为我只能返回停止名称,并且它并不是很有用,因为我实际上需要ID。

Many thanks for any tip. 非常感谢您的提示。

OK, after a fair bit of time I figured it out, thanks to the tip from joaquin. 好的,经过一段时间后,我想出了答案,这要归功于华金的提示。 It was indeed done by implementing custom adapter. 确实是通过实现自定义适配器来完成的。 And the HashMap was not very helpful in original goal. 而且HashMap对最初的目标不是很有帮助。 Below is the code, if someone stumbles upon a similar challenge. 如果有人偶然遇到类似的挑战,则下面是代码。

Activity: 活动:

// Members
private long currentStopId;
protected Map<String,String> lineMap;
protected ArrayList<Stop> stopMap;
protected String previousUrl = null;

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

    // Get the list of stops from resourse XML
    getStopInformation();

    // Enable auto-complete
    stopInput = (AutoCompleteTextView) findViewById(R.id.inputStopName);
    final HashMapAdapter adapter = new HashMapAdapter(this,R.layout.stop_list,stopMap);
    stopInput.setAdapter(adapter);

    // Add listener for auto-complete selection
    stopInput.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long rowId) {
            String selection = (String)parent.getItemAtPosition(position);

            // There we get the ID.
            currentStopId = parent.getItemIdAtPosition(position);
        }
    });
}

Adapter implementation: 适配器实现:

public class StopAdapter extends BaseAdapter implements Filterable {

private ArrayList<Stop> inputStopList;
private ArrayList<Stop> inputStopListClone;
private LayoutInflater lInflater;

/** Constructor */
public StopAdapter(Context context, int textViewResourceId, ArrayList<Stop> input) {
    lInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    inputStopList = input;
    inputStopListClone = inputStopList;
}

@Override
public int getCount() {
    return inputStopList.size();
}

@Override
public Object getItem(int i) {
    Stop value = inputStopList.get(i);
    return value.getStopName();
}

@Override
public long getItemId(int i) {
    Stop stop = inputStopList.get(i);
    long value = Long.parseLong(stop.getStopCode());
    return value;
}

@Override
public View getView(int i, View view, ViewGroup viewGroup) {
    View myView = view;

    // R.layout.stop_list created in res/layout
    if(myView == null)
        myView = lInflater.inflate(R.layout.stop_list,viewGroup, false);

    ((TextView) myView.findViewById(R.id.textView)).setText(getItem(i).toString());

    return myView;
}

/** Required by AutoCompleteTextView to filter suggestions. */
@Override
public Filter getFilter() {
    Filter filter = new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence charSequence) {
            FilterResults filterResults = new FilterResults();

            if(charSequence == null || charSequence.length() == 0) {
                ArrayList<Stop> originalValues = new ArrayList<Stop>(inputStopList);
                filterResults.count = originalValues.size();
                filterResults.values = originalValues;
            }
            else {
                ArrayList<Stop> newValues = new ArrayList<Stop>();

                // Note the clone - original list gets stripped
                for(Stop stop : inputStopListClone)
                {
                    String lowercase = stop.getStopName().toLowerCase();
                    if(lowercase.startsWith(charSequence.toString().toLowerCase()))
                        newValues.add(stop);
                }

                filterResults.count = newValues.size();
                filterResults.values = newValues;
            }
            return filterResults;
        }

        @Override
        protected void publishResults(CharSequence charSequence, FilterResults filterResults) {

            if(filterResults != null && filterResults.count > 0) {
                inputStopList = (ArrayList<Stop>)filterResults.values;
                notifyDataSetChanged();
            }
            else notifyDataSetInvalidated();
        }
    };
    return filter;
}

} }

You are using AutoCompleteTextView instead of MultiAutoCompleteTextView . 您正在使用AutoCompleteTextView而不是MultiAutoCompleteTextView

MultiAutoCompleteTextView is exactly what you need because it works exactly equal as AutoCompleteTextView with the difference that it can show more than one suggestion (if they exist) and lets the user choose only one of them. MultiAutoCompleteTextView正是您所需要的,因为它的工作原理与AutoCompleteTextView完全相同,不同之处在于它可以显示多个建议(如果存在),并且用户只能选择其中一项。

Reference Image: http://i.stack.imgur.com/9wMAv.png 参考图片: http : //i.stack.imgur.com/9wMAv.png

For a nice example check out Android Developers: http://developer.android.com/reference/android/widget/MultiAutoCompleteTextView.html 有关示例,请查看Android开发人员: http : //developer.android.com/reference/android/widget/MultiAutoCompleteTextView.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM