//功能:在AutocompleteTextView 裏輸入一個城市開頭名的字
//自動檢索有該字 的 城市android
一、先佈局界面 res/layout裏有2個xml文件ide
activity_main.xml佈局
代碼this
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>xml
<AutoCompleteTextView
android:id="@+id/autocompletetextview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:completionThreshold="1"
android:hint="請輸入城市名"
/>ci
</RelativeLayout>
-----------------------
citys_weather.xmlget
代碼it
<?xml version="1.0" encoding="UTF-8"?>
<citylist>
<p p_id = "01">
<pn>北京</pn>
<c c_id="0101"><cn>北京</cn>
<d d_id="101010100">北京</d>
<d d_id="101010200">海淀</d>
<d d_id="101010300">朝陽</d>
<d d_id="101010400">順義</d>
<d d_id="101010500">懷柔</d>
<d d_id="101010600">通州</d>
<d d_id="101010700">昌平</d>
<d d_id="101010800">延慶</d>
<d d_id="101010900">豐臺</d>
<d d_id="101011000">石景山</d>
<d d_id="101011100">大興</d>
<d d_id="101011200">房山</d>
<d d_id="101011300">密雲</d>
<d d_id="101011400">門頭溝</d>
<d d_id="101011500">平谷</d>
</c>
</p>
</citylist>
--------------------------
二、在MainActivity 裏實現功能io
代碼class
public class MainActivity extends Activity {private AutoCompleteTextView auto;private ArrayAdapter<String> c_adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //一、獲取res/layout裏面的xml文件名字 XmlPullParser parser = getResources().getXml(R.layout.citys_weather); auto = (AutoCompleteTextView) this.findViewById(R.id.autocompletetextview); //二、經過pull解析 把citys_weather.xml文件解析完後返回結果保存在list集合中 List<String> city_list = City_data(parser);//三、new一個ArrayAdapter適配器 -- 把集合裏的數據 丟到 適配器裏 c_adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,city_list); //四、把適配器(數據)綁定到AutoCompleteTextView裏 auto.setAdapter(c_adapter); }//pull解析 private List<String> City_data(XmlPullParser parser) { List<String> c_list = new ArrayList<String>(); try { int type = parser.getEventType(); while(type != XmlPullParser.END_DOCUMENT){ switch(type){ case XmlPullParser.START_TAG: if("d".equals(parser.getName())){ c_list.add(parser.nextText()); } break; } type = parser.next(); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return c_list; }}