80 likes | 94 Views
各種清單資料來源設定法. List – 取自於 string.xml. ArrayAdapter<CharSequence> adapter=ArrayAdapter.createFromResource(this, R.array.fruitName ,android.R.layout.simple_list_item_1); setListAdapter(adapter); ListView listview=getListView(); listview.setOnItemClickListener(listener);. string.xml.
E N D
List– 取自於string.xml • ArrayAdapter<CharSequence> adapter=ArrayAdapter.createFromResource(this,R.array.fruitName,android.R.layout.simple_list_item_1); • setListAdapter(adapter); • ListView listview=getListView(); • listview.setOnItemClickListener(listener);
string.xml • <?xml version="1.0" encoding="utf-8"?> • <resources> • <string name="app_name">ListAdaptive Test</string> • <string name="hello_world">Hello world!</string> • <string name="menu_settings">Settings</string> • <string-array name="fruitName"> • <item >Apple</item> • <item >Banana</item> • <item >Cherry</item> • <item >Mango</item> • <item >Orange</item> • <item >Pear</item> • <item >Strawberry</item> • </string-array> • </resources>
取值 • private AdapterView.OnItemClickListener listener=new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Toast.makeText(parent.getContext(),((TextView)view).getText(), Toast.LENGTH_LONG).show(); • } • };
List– 取自於宣告陣列 • String[] fruitName={“Apple”,“Banana”,“Cherry”,“Mango”,“Orange”,“Pear”,"Strawberry"}; • ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,fruitName); • ListView listView=(ListView)findViewById(R.id.listView1); • listView.setAdapter(adapter); • listView.setOnItemClickListener(listener);
點擊取值 • private AdapterView.OnItemClickListener listener=new AdapterView.OnItemClickListener() { • public void onItemClick(AdapterView<?> parent, View view, int position, long id) { • textView.setText(((TextView)view).getText()); • //textView.setText(String.valueOf(position)); • } • };
Spinner • ArrayAdapter<CharSequence> adapter= • ArrayAdapter.createFromResource (this,R.array.fruitName, android.R.layout.simple_spinner_dropdown_item); • Spinner spinner= (Spinner)findViewById(R.id.spinner1); • spinner.setAdapter(adapter); • spinner.setOnItemSelectedListener(listener);
點擊取值 • private Spinner.OnItemSelectedListener listener=new Spinner.OnItemSelectedListener() { • public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { • Toast.makeText(parent.getContext(), • "Selected Item Position: "+String.valueOf(pos), • Toast.LENGTH_LONG).show(); • } • public void onNothingSelected(AdapterView<?> parent) { • } • };