简体   繁体   English

android:带有自定义适配器的AutoCompleteTextView

[英]android: AutoCompleteTextView with custom adapter

I wrote a custom adapter class extending BaseAdapter implementing Filterable to use with an AutoCompleteTextView. 我编写了一个自定义适配器类,扩展了BaseAdapter,实现了Filterable以便与AutoCompleteTextView一起使用。 The filtering and selecting is working fine. 筛选和选择工作正常。

The only problem is, if an item from the list is clicked, the AutoCompleteTextView seems to automatically call the adapters getItem(int position) method and sets its text to getItem(position).toString() . 唯一的问题是,如果单击列表中的某个项目,则AutoCompleteTextView似乎会自动调用适配器的getItem(int position)方法,并将其文本设置为getItem(position).toString() I dont want this behaviour as Im using custom Objects in the base adapter and this is resulting into strings like "ClassName [id=xx, variable1=var1]" put into the TextView. 我不希望这种行为成为Im,因为我在基本适配器中使用自定义对象,这导致将诸如"ClassName [id=xx, variable1=var1]"之类的字符串放入TextView中。

I tried setting my own OnItemClickListener and OnItemSelectedListener so far, but this seems to only quickly override the above set string instead of directly writing my custom String. 到目前为止,我尝试设置自己的OnItemClickListener和OnItemSelectedListener,但这似乎只能快速覆盖上面设置的字符串,而不是直接编写我的自定义String。 How can I disable this default string? 如何禁用此默认字符串?

Oh, and overriding the Objects toString() method is not an option in this case. 哦,在这种情况下,不能重写Objects的toString()方法。

Any ideas? 有任何想法吗? regards danijoo 问候danijoo

// try this
 autoCompleteText.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> adapterView, View arg1, int position, long arg3) {
                String str = (String) adapterView.getItemAtPosition(position);
                autoCompleteText.setText(str);
            }
        });

I had the same problem and I solved it with the following: 我遇到了同样的问题,并通过以下方法解决了问题:

private AutoCompleteTextView actv;
CustomAdapter adapter = new CustomAdapter(context, resource, data);
    actv.setAdapter(adapter);
    actv.setOnItemClickListener(new AdapterView.OnItemClickListener()
    {
        @Override
        public void onItemClick(AdapterView<?> av, View view, int index, long arg3)
        {
            CustomAdapter adapter = (CustomAdapter)av.getAdapter();
            Pair customObject = (Pair<Integer, String>) adapter.getItemAtPosition(index);
        }
    });

You have to create a custom getItemAtPosition method inside your CustomAdapter . 您必须在CustomAdapter创建一个自定义getItemAtPosition方法。 In this way you do not have to override the getItem(int position) requested by the AutoCompleteTextView and you can use instead getItemAtPosition to return your desired CustomObject . 这样,您不必重写AutoCompleteTextView请求的getItem(int position) ,而可以使用getItemAtPosition来返回所需的CustomObject

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

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