含一个AutoCompleteTextView和一个imagView。textView可以根据输入提示城市名字。ImageView用于返回主页面,并传递城市代码给MainActiviy。
一、变量
HashMap用于匹配城市代码和城市名字
private AutoCompleteTextView searchCityCodeAutoCompleteTextView;
private ImageView searchFinishImageView;
private HashMap<String, String> cityNameKeyCityNameValueHashMap;
private Handler readXMLFinishHandler;
二、Handler
sendMessage()中编写了adapter适配器方法。***setAutoCompleteTextViewAdapter() *** 用set 获取所有城市名称的数组,并把把citySet中的数据放到String数组中。
readXMLFinishHandler = new Handler(){
public void handleMessage(Message msg) {
setAutoCompleteTextViewAdapter();
};
private void setAutoCompleteTextViewAdapter() {
Set<String> cityNameSet = cityNameKeyCityNameValueHashMap.keySet();
String[] cityNames = new String[cityNameSet.size()];
cityNameSet.toArray(cityNames);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
SearchCityCodeActivity.this, android.R.layout.simple_list_item_1,
cityNames);
searchCityCodeAutoCompleteTextView.setAdapter(adapter);//设置适配器
searchCityCodeAutoCompleteTextView.setThreshold(1);//指定从第几个显示提示
};
};
三、OnCreate()方法
findViews();
setLisener();
getCityCodeFromXML();
四、setLisener();
-
searchFinishImageView
先异常处理,如果得到的字符串为空,则显示提示。
String cityName = searchCityCodeAutoCompleteTextView.getText().toString().trim();
if (TextUtils.isEmpty(cityName)) {
searchCityCodeAutoCompleteTextView.setError("请输入城市名称");
return;
}//把城市名作为键,去hashmap里取值
String cityCodeString = cityNameKeyCityNameValueHashMap.get(cityName);
if (TextUtils.isEmpty(cityCodeString)) {
searchCityCodeAutoCompleteTextView.setError("没有此城市的信息");
return;
}
int cityCode = Integer.valueOf(cityCodeString);
setResult(cityCode);
finish();
}//cityCode 有值,把cityCode转化为Int型。返回给mainActivity。