2017-03-29 82 views
0

我有一個AutoCompleteTextView,並根據其中的更改,它顯示下拉列表與來自服務器的數據。通過更改每個符號後的偵聽器,我向服務器發出請求並獲取一些列表。AutoCompleteTextView適配器問題

之後我顯示AutoCompleteTextView該列表,在代碼中,我通過這種方式做到這一點:

List<String> list = new ArrayList<String>(); 
for (int i = 0; i < jsonArray.length(); i++) { 
    list.add(jsonArray.getJSONObject(i).getString("title")); 
} 
String[] cities = list.toArray(new String[list.size()]); 
ArrayAdapter<String> adapter = new ArrayAdapter<String>(DistanceCalculation.this, R.layout.support_simple_spinner_dropdown_item, cities); 
AutoCompleteTextView my = (AutoCompleteTextView) myView; 
my.setAdapter(adapter); 

問題是oftenly只顯示列表中的第一個元素,而長後單擊它顯示完整的列表。我不明白爲什麼會發生。

對不起,工程預先感謝!你也可以查看下面的代碼的其餘部分:

XML部分:

<AutoCompleteTextView 
android:id="@+id/from" 
android:layout_width="match_parent" 
android:layout_height="wrap_content" 
android:layout_alignParentLeft="true" 
android:layout_alignParentStart="true" 
android:layout_marginTop="15dp" 
android:background="@drawable/td_inp" 
android:hint="Откуда" 
android:paddingBottom="5dp" 
android:paddingLeft="5dp" 
android:paddingRight="5dp" 
android:paddingTop="5dp" 
android:textColor="#000" 
android:textColorHint="#757575" /> 

AutoCompleteTextView及其的onCreate

tCityFrom = (AutoCompleteTextView) findViewById(R.id.from); 
tCityFrom.addTextChangedListener(new TextWatcher() { 
    public void afterTextChanged(Editable s) { 
     if(s.length() >= 2) load_city(ssid, s.toString(),tCityFrom); 
    } 
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {} 
    public void onTextChanged(CharSequence s, int start, int before, int count) {} 
}); 
+0

你能提供更多的代碼嗎? – tahsinRupam

+0

@tahsinRupam,你可以檢查它嗎? – Bek

+0

你的load_city()是做什麼的?我是否也可以要求添加該方法? – tahsinRupam

回答

1

監聽我假設你想顯示自動完成建議根據什麼用戶類型。你必須從服務器onTextChanged()加載數據:

tCityFrom = (AutoCompleteTextView) findViewById(R.id.from); 
tCityFrom.addTextChangedListener(new TextWatcher() { 
    public void afterTextChanged(Editable s) { } 
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {} 
    public void onTextChanged(CharSequence s, int start, int before, int count) { 
     if(s.length() >= 2) 
      load_city(ssid, s.toString(),tCityFrom); 
    } 
}); 

然後聲明的ArrayList適配器全球:

List<String> list; 
ArrayAdapter<String> adapter; 

onCreate()

list = new ArrayList<String>(); 
adapter = new ArrayAdapter<String>(DistanceCalculation.this, R.layout.support_simple_spinner_dropdown_item, cities); 
AutoCompleteTextView my = (AutoCompleteTextView) myView; 
my.setAdapter(adapter); 

更換你的第一個代碼SN load_city()附帶以下代碼:

list.clear(); 
for (int i = 0; i < jsonArray.length(); i++) { 
    list.add(jsonArray.getJSONObject(i).getString("title")); 
} 
adapter.notifyDataSetChanged(); 

希望這會有所幫助。

+0

notifyDataSetChanged()修復了我的問題,thx! – Bek

+0

不客氣:) – tahsinRupam