簡體   English   中英

Android AutoCompleteTextView顯示錯誤建議

[英]Android AutoCompleteTextView showing wrong suggestions

在決定使用自定義適配器之前,我讓AutoCompleteTextView完美地工作了,這樣我可以自定義每行的外觀。 這是現在發生的情況:

在此處輸入圖片說明

如您所見,該建議是錯誤的。 所發生的是在我鍵入內容時,它顯示了正確的建議數量 ,但是它們的實際名稱是列表中的第一個。 因此,在這一點上,它應該僅顯示一個建議,即Texas A&M,但它僅顯示列表中的第一個建議。 這是我實現適配器的方式。

//setup filter
List<String> allCollegesList = new ArrayList<String>();
for(College c : MainActivity.collegeList)
{
    allCollegesList.add(c.getName());
}
AutoCompleteDropdownAdapter adapter = new AutoCompleteDropdownAdapter(main, R.layout.list_row_dropdown, allCollegesList);
//the old way of using the adapter, which worked fine
//ArrayAdapter<String> adapter = new ArrayAdapter<String>(main, android.R.layout.simple_dropdown_item_1line, allCollegesList);
textView.setAdapter(adapter);

以及我實際的適配器類:

public class AutoCompleteDropdownAdapter extends ArrayAdapter<String>{

    MainActivity main;
    int rowLayout;
    List<String> allCollegesList;

    public AutoCompleteDropdownAdapter(MainActivity main, int rowLayout, List<String> allCollegesList) {
        super(main, rowLayout, allCollegesList);
        this.main = main;
        this.rowLayout = rowLayout;
        this.allCollegesList = allCollegesList;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        try{

            if(convertView==null){
                // inflate the layout
                LayoutInflater inflater = ((MainActivity) main).getLayoutInflater();
                convertView = inflater.inflate(rowLayout, parent, false);
            }

            // object item based on the position
            String college = allCollegesList.get(position);

            // get the TextView and then set the text (item name) and tag (item ID) values
            TextView collegeTextView = (TextView) convertView.findViewById(R.id.dropDownText);
            collegeTextView.setText(college);
            collegeTextView.setTypeface(FontManager.light);

        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return convertView;

    }
}

這里發生的是,當AutoCompleteTextView調用ArrayAdaptergetFilter方法時,將返回一個Filter ,它負責過濾ArrayAdapter ,而不是對allCollegesList的過濾。 鍵入第一個字符時,將調用Filter的方法,並且ArrayAdapter在第一個位置( 0, 1, ... )具有已過濾的元素。 但是,當AutoCompleteTextView使用您的實現獲取視圖時。 您可以像未進行任何過濾一樣使用列表,並使用未過濾列表的前幾個元素。

您也可以通過覆蓋適配器的getFilter方法來過濾自己的列表。 但這將超出必要的編碼范圍。

您可以使用ArrayAdapter的方法,而不是您自己的列表,而是:

采用

String college = getItem(position);

代替

String college = allCollegesList.get(position);

順便說一句:

您也可以使用getContext()方法從parent獲取上下文。 這樣,您可以將Adapter與MainActivity分離。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM