如何在spinner
列表中首先显示所选项目?
假设从Rainy
检索到MySQL
,现在它应首先显示Rainy item
。我该如何实现这一目标?
Spinner Weather;
private void showEmployee(String json){
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY);
JSONObject c = result.getJSONObject(0);
String weather = c.getString(Config.TAG_WEATHER);
RetrieveWeather(weather);
// what should add here
} catch (JSONException e) {
e.printStackTrace();
}
}
public void RetrieveWeather(String a)
{
String[] arr = new String[]{"Sunny","Cloudy","Rainy","Thunderstorm"};
List<String> list = new ArrayList<String>();
String weather = a;
list.add(weather);
for(String s:arr){
if(!list.contains(s)){
list.add(s);
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Weather.setAdapter(adapter);
}
答案 0 :(得分:0)
尝试以下方法:
Spinner Weather;
String weather;
int pos = 0;
String[] arr = new String[]{"Sunny","Cloudy","Rainy","Thunderstorm"};
private void showEmployee(String json){
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY);
JSONObject c = result.getJSONObject(0);
weather = c.getString(Config.TAG_WEATHER);
RetrieveWeather(weather);
// what should add here
Weather.setSelection(pos);
} catch (JSONException e) {
e.printStackTrace();
}
}
public void RetrieveWeather(String a)
{
List<String> list = new ArrayList<String>();
String weather = a;
list.add(weather);
for(String s:arr){
if(!list.contains(s)){
list.add(s);
}
}
for(int i=0;i<list.size();i++)
{
if(weather.equals(list.get(i)))
{
pos = i;
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Weather.setAdapter(adapter);
}