在android開發中ListView是比較常用的組件,它以列表的形式展示具體內容,並且能夠根據數據的長度自適應顯示。
- packagecom.ray.test;
- importjava.util.ArrayList;
- importjava.util.HashMap;
- importandroid.app.Activity;
- importandroid.os.Bundle;
- importandroid.view.ContextMenu;
- importandroid.view.MenuItem;
- importandroid.view.View;
- importandroid.view.ContextMenu.ContextMenuInfo;
- importandroid.view.View.OnCreateContextMenuListener;
- importandroid.widget.AdapterView;
- importandroid.widget.ListView;
- importandroid.widget.SimpleAdapter;
- importandroid.widget.AdapterView.OnItemClickListener;
- publicclassTestListViewextendsActivity{
- @Override
- publicvoidonCreate(BundlesavedInstanceState){
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- //綁定Layout裡面的ListView
- ListViewlist=(ListView)findViewById(R.id.ListView01);
- //生成動態數組,加入數據
- ArrayList<HashMap<String,Object>>listItem=newArrayList<HashMap<String,Object>>();
- for(inti=0;i<10;i++)
- {
- HashMap<String,Object>map=newHashMap<String,Object>();
- map.put("ItemImage",R.drawable.checked);//圖像資源的ID
- map.put("ItemTitle","Level"+i);
- map.put("ItemText","Finishedin1Min54Secs,70Moves!");
- listItem.add(map);
- }
- //生成適配器的Item和動態數組對應的元素
- SimpleAdapterlistItemAdapter=newSimpleAdapter(this,listItem,//數據源
- R.layout.list_items,//ListItem的XML實現
- //動態數組與ImageItem對應的子項
- newString[]{"ItemImage","ItemTitle","ItemText"},
- //ImageItem的XML檔案裡面的一個ImageView,兩個TextViewID
- newint[]{R.id.ItemImage,R.id.ItemTitle,R.id.ItemText}
- );
- //添加並且顯示
- list.setAdapter(listItemAdapter);
- //添加點擊
- list.setOnItemClickListener(newOnItemClickListener(){
- @Override
- publicvoidonItemClick(AdapterView<?>arg0,Viewarg1,intarg2,
- longarg3){
- setTitle("點擊第"+arg2+"個項目");
- }
- });
- //添加長按點擊
- list.setOnCreateContextMenuListener(newOnCreateContextMenuListener(){
- @Override
- publicvoidonCreateContextMenu(ContextMenumenu,Viewv,ContextMenuInfomenuInfo){
- menu.setHeaderTitle("長按選單-ContextMenu");
- menu.add(0,0,0,"彈出長按選單0");
- menu.add(0,1,0,"彈出長按選單1");
- }
- });
- }
- //長按選單回響函式
- @Override
- publicbooleanonContextItemSelected(MenuItemitem){
- setTitle("點擊了長按選單裡面的第"+item.getItemId()+"個項目");
- returnsuper.onContextItemSelected(item);
- }
- }