小菜毛毛技術(shù)分享

          與大家共同成長(zhǎng)

            BlogJava :: 首頁(yè) :: 聯(lián)系 :: 聚合  :: 管理
            164 Posts :: 141 Stories :: 94 Comments :: 0 Trackbacks
          轉(zhuǎn)載自:http://www.cnblogs.com/allin/archive/2010/05/11/1732200.html
          在android開發(fā)中ListView是比較常用的組件,它以列表的形式展示具體內(nèi)容,并且能夠根據(jù)數(shù)據(jù)的長(zhǎng)度自適應(yīng)顯示。抽空把對(duì)ListView的使用做了整理,并寫了個(gè)小例子,如下圖。

           

           列表的顯示需要三個(gè)元素:

          1.ListVeiw 用來展示列表的View。

          2.適配器 用來把數(shù)據(jù)映射到ListView上的中介。

          3.?dāng)?shù)據(jù)    具體的將被映射的字符串,圖片,或者基本組件。

          根據(jù)列表的適配器類型,列表分為三種,ArrayAdapter,SimpleAdapter和SimpleCursorAdapter

          其中以ArrayAdapter最為簡(jiǎn)單,只能展示一行字。SimpleAdapter有最好的擴(kuò)充性,可以自定義出各種效果。SimpleCursorAdapter可以認(rèn)為是SimpleAdapter對(duì)數(shù)據(jù)庫(kù)的簡(jiǎn)單結(jié)合,可以方面的把數(shù)據(jù)庫(kù)的內(nèi)容以列表的形式展示出來。

           

           我們從最簡(jiǎn)單的ListView開始:

           

          01 /**
          02  * @author allin
          03  *
          04  */
          05 public class MyListView extends Activity {
          06   
          07     private ListView listView;
          08     //private List<String> data = new ArrayList<String>();
          09     @Override
          10     public void onCreate(Bundle savedInstanceState){
          11         super.onCreate(savedInstanceState);
          12           
          13         listView = new ListView(this);
          14         listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1,getData()));
          15         setContentView(listView);
          16     }
          17       
          18       
          19       
          20     private List<String> getData(){
          21           
          22         List<String> data = new ArrayList<String>();
          23         data.add("測(cè)試數(shù)據(jù)1");
          24         data.add("測(cè)試數(shù)據(jù)2");
          25         data.add("測(cè)試數(shù)據(jù)3");
          26         data.add("測(cè)試數(shù)據(jù)4");
          27           
          28         return data;
          29     }
          30 }

           

           

          上面代碼使用了ArrayAdapter(Context context, int textViewResourceId, List<T> objects)來裝配數(shù)據(jù),要裝配這些數(shù)據(jù)就需要一個(gè)連接ListView視圖對(duì)象和數(shù)組數(shù)據(jù)的適配器來兩者的適配工作,ArrayAdapter的構(gòu)造需要三個(gè)參數(shù),依次為this,布局文件(注意這里的布局文件描述的是列表的每一行的布局,android.R.layout.simple_list_item_1是系統(tǒng)定義好的布局文件只顯示一行文字,數(shù)據(jù)源(一個(gè)List集合)。同時(shí)用setAdapter()完成適配的最后工作。運(yùn)行后的現(xiàn)實(shí)結(jié)構(gòu)如下圖:

           

           

          SimpleCursorAdapter

            sdk的解釋是這樣的:An easy adapter to map columns from a cursor to TextViews or ImageViews defined in an XML file. You can specify which columns you want, which views you want to display the columns, and the XML file that defines the appearance of these views。簡(jiǎn)單的說就是方便把從游標(biāo)得到的數(shù)據(jù)進(jìn)行列表顯示,并可以把指定的列映射到對(duì)應(yīng)的TextView中。

            下面的程序是從電話簿中把聯(lián)系人顯示到類表中。先在通訊錄中添加一個(gè)聯(lián)系人作為數(shù)據(jù)庫(kù)的數(shù)據(jù)。然后獲得一個(gè)指向數(shù)據(jù)庫(kù)的Cursor并且定義一個(gè)布局文件(當(dāng)然也可以使用系統(tǒng)自帶的)。

           

          01 /**
          02  * @author allin
          03  *
          04  */
          05 public class MyListView2 extends Activity {
          06   
          07     private ListView listView;
          08     //private List<String> data = new ArrayList<String>();
          09     @Override
          10     public void onCreate(Bundle savedInstanceState){
          11         super.onCreate(savedInstanceState);
          12           
          13         listView = new ListView(this);
          14           
          15         Cursor cursor = getContentResolver().query(People.CONTENT_URI, null, null, null, null);
          16         startManagingCursor(cursor);
          17           
          18         ListAdapter listAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_expandable_list_item_1, 
          19                 cursor,
          20                 new String[]{People.NAME}, 
          21                 new int[]{android.R.id.text1});
          22           
          23         listView.setAdapter(listAdapter);
          24         setContentView(listView);
          25     }
          26       
          27       
          28 }

           

           

           Cursor cursor = getContentResolver().query(People.CONTENT_URI, null, null, null, null);先獲得一個(gè)指向系統(tǒng)通訊錄數(shù)據(jù)庫(kù)的Cursor對(duì)象獲得數(shù)據(jù)來源。

           startManagingCursor(cursor);我們將獲得的Cursor對(duì)象交由Activity管理,這樣Cursor的生命周期和Activity便能夠自動(dòng)同步,省去自己手動(dòng)管理Cursor。

           SimpleCursorAdapter 構(gòu)造函數(shù)前面3個(gè)參數(shù)和ArrayAdapter是一樣的,最后兩個(gè)參數(shù):一個(gè)包含數(shù)據(jù)庫(kù)的列的String型數(shù)組,一個(gè)包含布局文件中對(duì)應(yīng)組件id的int型數(shù)組。其作用是自動(dòng)的將String型數(shù)組所表示的每一列數(shù)據(jù)映射到布局文件對(duì)應(yīng)id的組件上。上面的代碼,將NAME列的數(shù)據(jù)一次映射到布局文件的id為text1的組件上。

          注意:需要在AndroidManifest.xml中如權(quán)限:<uses-permission android:name="android.permission.READ_CONTACTS"></uses-permission>

          運(yùn)行后效果如下圖:

           

           

          SimpleAdapter

           

          simpleAdapter的擴(kuò)展性最好,可以定義各種各樣的布局出來,可以放上ImageView(圖片),還可以放上Button(按鈕),CheckBox(復(fù)選框)等等。下面的代碼都直接繼承了ListActivity,ListActivity和普通的Activity沒有太大的差別,不同就是對(duì)顯示ListView做了許多優(yōu)化,方面顯示而已。

          下面的程序是實(shí)現(xiàn)一個(gè)帶有圖片的類表。

          首先需要定義好一個(gè)用來顯示每一個(gè)列內(nèi)容的xml

          vlist.xml

           

          01 <?xml version="1.0" encoding="utf-8"?>
          02 <LinearLayout xmlns:android="
          03     android:orientation="horizontal" android:layout_width="fill_parent"
          04     android:layout_height="fill_parent">
          05   
          06   
          07     <ImageView android:id="@+id/img" 
          08         android:layout_width="wrap_content"
          09         android:layout_height="wrap_content" 
          10         android:layout_margin="5px"/>
          11   
          12     <LinearLayout android:orientation="vertical"
          13         android:layout_width="wrap_content" 
          14         android:layout_height="wrap_content">
          15   
          16         <TextView android:id="@+id/title" 
          17             android:layout_width="wrap_content"
          18             android:layout_height="wrap_content" 
          19             android:textColor="#FFFFFFFF"
          20             android:textSize="22px" />
          21         <TextView android:id="@+id/info" 
          22             android:layout_width="wrap_content"
          23             android:layout_height="wrap_content" 
          24             android:textColor="#FFFFFFFF"
          25             android:textSize="13px" />
          26   
          27     </LinearLayout>
          28   
          29   
          30 </LinearLayout>

          下面是實(shí)現(xiàn)代碼:

           

          01 /**
          02  * @author allin
          03  
          04  */
          05 public class MyListView3 extends ListActivity {
          06   
          07   
          08     // private List<String> data = new ArrayList<String>();
          09     @Override
          10     public void onCreate(Bundle savedInstanceState) {
          11         super.onCreate(savedInstanceState);
          12   
          13         SimpleAdapter adapter = new SimpleAdapter(this,getData(),R.layout.vlist,
          14                 new String[]{"title","info","img"},
          15                 new int[]{R.id.title,R.id.info,R.id.img});
          16         setListAdapter(adapter);
          17     }
          18   
          19     private List<Map<String, Object>> getData() {
          20         List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
          21   
          22         Map<String, Object> map = new HashMap<String, Object>();
          23         map.put("title", "G1");
          24         map.put("info", "google 1");
          25         map.put("img", R.drawable.i1);
          26         list.add(map);
          27   
          28         map = new HashMap<String, Object>();
          29         map.put("title", "G2");
          30         map.put("info", "google 2");
          31         map.put("img", R.drawable.i2);
          32         list.add(map);
          33   
          34         map = new HashMap<String, Object>();
          35         map.put("title", "G3");
          36         map.put("info", "google 3");
          37         map.put("img", R.drawable.i3);
          38         list.add(map);
          39           
          40         return list;
          41     }
          42 }

           

           

          使用simpleAdapter的數(shù)據(jù)用一般都是HashMap構(gòu)成的List,list的每一節(jié)對(duì)應(yīng)ListView的每一行。HashMap的每個(gè)鍵值數(shù)據(jù)映射到布局文件中對(duì)應(yīng)id的組件上。因?yàn)橄到y(tǒng)沒有對(duì)應(yīng)的布局文件可用,我們可以自己定義一個(gè)布局vlist.xml。下面做適配,new一個(gè)SimpleAdapter參數(shù)一次是:this,布局文件(vlist.xml),HashMap的 title 和 info,img。布局文件的組件id,title,info,img。布局文件的各組件分別映射到HashMap的各元素上,完成適配。

          運(yùn)行效果如下圖:

           

           

           

           

          有按鈕的ListView

           

          但是有時(shí)候,列表不光會(huì)用來做顯示用,我們同樣可以在在上面添加按鈕。添加按鈕首先要寫一個(gè)有按鈕的xml文件,然后自然會(huì)想到用上面的方法定義一個(gè)適配器,然后將數(shù)據(jù)映射到布局文件上。但是事實(shí)并非這樣,因?yàn)榘粹o是無法映射的,即使你成功的用布局文件顯示出了按鈕也無法添加按鈕的響應(yīng),這時(shí)就要研究一下ListView是如何現(xiàn)實(shí)的了,而且必須要重寫一個(gè)類繼承BaseAdapter。下面的示例將顯示一個(gè)按鈕和一個(gè)圖片,兩行字如果單擊按鈕將刪除此按鈕的所在行。并告訴你ListView究竟是如何工作的。效果如下:

           

           

          vlist2.xml

           

          01 <?xml version="1.0" encoding="utf-8"?>
          02 <LinearLayout xmlns:android="
          03     android:orientation="horizontal" 
          04     android:layout_width="fill_parent"
          05     android:layout_height="fill_parent">
          06   
          07   
          08     <ImageView android:id="@+id/img" 
          09         android:layout_width="wrap_content"
          10         android:layout_height="wrap_content" 
          11         android:layout_margin="5px"/>
          12   
          13     <LinearLayout android:orientation="vertical"
          14         android:layout_width="wrap_content" 
          15         android:layout_height="wrap_content">
          16   
          17         <TextView android:id="@+id/title" 
          18             android:layout_width="wrap_content"
          19             android:layout_height="wrap_content" 
          20             android:textColor="#FFFFFFFF"
          21             android:textSize="22px" />
          22         <TextView android:id="@+id/info" 
          23             android:layout_width="wrap_content"
          24             android:layout_height="wrap_content" 
          25             android:textColor="#FFFFFFFF"
          26             android:textSize="13px" />
          27   
          28     </LinearLayout>
          29   
          30   
          31     <Button android:id="@+id/view_btn"
          32         android:layout_width="wrap_content"
          33         android:layout_height="wrap_content"
          34         android:text="@string/s_view_btn"
          35         android:layout_gravity="bottom|right" />
          36 </LinearLayout>

          程序代碼:

           

          001 /**
          002  * @author allin
          003  
          004  */
          005 public class MyListView4 extends ListActivity {
          006   
          007   
          008     private List<Map<String, Object>> mData;
          009       
          010     @Override
          011     public void onCreate(Bundle savedInstanceState) {
          012         super.onCreate(savedInstanceState);
          013         mData = getData();
          014         MyAdapter adapter = new MyAdapter(this);
          015         setListAdapter(adapter);
          016     }
          017   
          018     private List<Map<String, Object>> getData() {
          019         List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
          020   
          021         Map<String, Object> map = new HashMap<String, Object>();
          022         map.put("title", "G1");
          023         map.put("info", "google 1");
          024         map.put("img", R.drawable.i1);
          025         list.add(map);
          026   
          027         map = new HashMap<String, Object>();
          028         map.put("title", "G2");
          029         map.put("info", "google 2");
          030         map.put("img", R.drawable.i2);
          031         list.add(map);
          032   
          033         map = new HashMap<String, Object>();
          034         map.put("title", "G3");
          035         map.put("info", "google 3");
          036         map.put("img", R.drawable.i3);
          037         list.add(map);
          038           
          039         return list;
          040     }
          041       
          042     // ListView 中某項(xiàng)被選中后的邏輯
          043     @Override
          044     protected void onListItemClick(ListView l, View v, int position, long id) {
          045           
          046         Log.v("MyListView4-click", (String)mData.get(position).get("title"));
          047     }
          048       
          049     /**
          050      * listview中點(diǎn)擊按鍵彈出對(duì)話框
          051      */
          052     public void showInfo(){
          053         new AlertDialog.Builder(this)
          054         .setTitle("我的listview")
          055         .setMessage("介紹...")
          056         .setPositiveButton("確定", new DialogInterface.OnClickListener() {
          057             @Override
          058             public void onClick(DialogInterface dialog, int which) {
          059             }
          060         })
          061         .show();
          062           
          063     }
          064       
          065       
          066       
          067     public final class ViewHolder{
          068         public ImageView img;
          069         public TextView title;
          070         public TextView info;
          071         public Button viewBtn;
          072     }
          073       
          074       
          075     public class MyAdapter extends BaseAdapter{
          076   
          077         private LayoutInflater mInflater;
          078           
          079           
          080         public MyAdapter(Context context){
          081             this.mInflater = LayoutInflater.from(context);
          082         }
          083         @Override
          084         public int getCount() {
          085             // TODO Auto-generated method stub
          086             return mData.size();
          087         }
          088   
          089         @Override
          090         public Object getItem(int arg0) {
          091             // TODO Auto-generated method stub
          092             return null;
          093         }
          094   
          095         @Override
          096         public long getItemId(int arg0) {
          097             // TODO Auto-generated method stub
          098             return 0;
          099         }
          100   
          101         @Override
          102         public View getView(int position, View convertView, ViewGroup parent) {
          103               
          104             ViewHolder holder = null;
          105             if (convertView == null) {
          106                   
          107                 holder=new ViewHolder();  
          108                   
          109                 convertView = mInflater.inflate(R.layout.vlist2, null);
          110                 holder.img = (ImageView)convertView.findViewById(R.id.img);
          111                 holder.title = (TextView)convertView.findViewById(R.id.title);
          112                 holder.info = (TextView)convertView.findViewById(R.id.info);
          113                 holder.viewBtn = (Button)convertView.findViewById(R.id.view_btn);
          114                 convertView.setTag(holder);
          115                   
          116             }else {
          117                   
          118                 holder = (ViewHolder)convertView.getTag();
          119             }
          120               
          121               
          122             holder.img.setBackgroundResource((Integer)mData.get(position).get("img"));
          123             holder.title.setText((String)mData.get(position).get("title"));
          124             holder.info.setText((String)mData.get(position).get("info"));
          125               
          126             holder.viewBtn.setOnClickListener(new View.OnClickListener() {
          127                   
          128                 @Override
          129                 public void onClick(View v) {
          130                     showInfo();                 
          131                 }
          132             });
          133               
          134               
          135             return convertView;
          136         }
          137           
          138     }
          139       
          140       
          141       
          142       
          143 }

           

           

           

            下面將對(duì)上述代碼,做詳細(xì)的解釋,listView在開始繪制的時(shí)候,系統(tǒng)首先調(diào)用getCount()函數(shù),根據(jù)他的返回值得到listView的長(zhǎng)度(這也是為什么在開始的第一張圖特別的標(biāo)出列表長(zhǎng)度),然后根據(jù)這個(gè)長(zhǎng)度,調(diào)用getView()逐一繪制每一行。如果你的getCount()返回值是0的話,列表將不顯示同樣return 1,就只顯示一行。

           

            系統(tǒng)顯示列表時(shí),首先實(shí)例化一個(gè)適配器(這里將實(shí)例化自定義的適配器)。當(dāng)手動(dòng)完成適配時(shí),必須手動(dòng)映射數(shù)據(jù),這需要重寫getView()方法。系統(tǒng)在繪制列表的每一行的時(shí)候?qū)⒄{(diào)用此方法。getView()有三個(gè)參數(shù),position表示將顯示的是第幾行,covertView是從布局文件中inflate來的布局。我們用LayoutInflater的方法將定義好的vlist2.xml文件提取成View實(shí)例用來顯示。然后將xml文件中的各個(gè)組件實(shí)例化(簡(jiǎn)單的findViewById()方法)。這樣便可以將數(shù)據(jù)對(duì)應(yīng)到各個(gè)組件上了。但是按鈕為了響應(yīng)點(diǎn)擊事件,需要為它添加點(diǎn)擊監(jiān)聽器,這樣就能捕獲點(diǎn)擊事件。至此一個(gè)自定義的listView就完成了,現(xiàn)在讓我們回過頭從新審視這個(gè)過程。系統(tǒng)要繪制ListView了,他首先獲得要繪制的這個(gè)列表的長(zhǎng)度,然后開始繪制第一行,怎么繪制呢?調(diào)用getView()函數(shù)。在這個(gè)函數(shù)里面首先獲得一個(gè)View(實(shí)際上是一個(gè)ViewGroup),然后再實(shí)例并設(shè)置各個(gè)組件,顯示之。好了,繪制完這一行了。那 再繪制下一行,直到繪完為止。在實(shí)際的運(yùn)行過程中會(huì)發(fā)現(xiàn)listView的每一行沒有焦點(diǎn)了,這是因?yàn)锽utton搶奪了listView的焦點(diǎn),只要布局文件中將Button設(shè)置為沒有焦點(diǎn)就OK了。

           

          運(yùn)行效果如下圖:

           

           

          源碼下載

          posted on 2010-11-14 16:28 小菜毛毛 閱讀(2049) 評(píng)論(0)  編輯  收藏 所屬分類: andriod
          主站蜘蛛池模板: 连山| 大石桥市| 临猗县| 萍乡市| 左权县| 合阳县| 登封市| 申扎县| 集贤县| 万盛区| 祁门县| 班玛县| 雷州市| 高雄市| 民县| 甘孜县| 崇义县| 吉首市| 四会市| 昭觉县| 信宜市| 镇江市| 宁武县| 永昌县| 绵竹市| 莱州市| 上思县| 太谷县| 东兰县| 昌吉市| 高唐县| 辛集市| 尉犁县| 鄂尔多斯市| 邛崃市| 彰武县| 临武县| 罗平县| 阿城市| 泰顺县| 吉林省|