安卓ListView的使用

來源:互聯網
上載者:User

標籤:protected   override   protect   樣式   param   包括   檔案中   getc   min   

1.簡單介紹ListView

      listview是一個以垂直方式在項目中顯示視圖的列表。是一種不能實現確定視圖中的內容的適配器視圖(adapter view)。資料和視圖的綁定,需要通過繼承ListViewAdapter介面的適配器實現。確保當上下滾動的時候,能夠動態重新整理視圖內容。通常我們都會自訂一個繼承自BaseAdapter(已繼承ListViewAdapter),ArrayAdapter(繼承自BaseAdapter),SimpleAdapter(繼承自BaseAdapter)的類,重寫getView()方法,實現自己想要的功能。

      getView方法詳情

   View getView (int position, View convertView, ViewGroup parent)
Get a View that displays the data at the specified position in the data set.
You can either create a View manually or inflate it from an XML layout file.
When the View is inflated, the parent View (GridView, ListView...) will apply
default layout parameters unless you use inflate(int, android.view.ViewGroup, boolean) to
specify a root view and to prevent attachment to the root
備忘:使用適配器構建布局

如果布局的內容是屬於動態或未預先確定的內容,您可以使用這樣一種布局:在運行時通過子類 AdapterView 用視圖填充布局。 AdapterView 類的子類使用 Adapter 將資料與其布局綁定。

Adapter 充當資料來源與 AdapterView 布局之間的中間人—Adapter(從數組或資料庫查詢等來源)檢索資料,並將每個條目轉換為可以添加到 AdapterView 布局中的視圖。

          適配器支援的常見布局包括:

           

    使用資料填充適配器視圖       

    您可以通過將 AdapterView 執行個體與 Adapter 綁定來填充 AdapterView(如 ListView 或 GridView),此操作會從外部來源檢索資料,並建立表示每個資料條目的 View

Android 提供了幾個 Adapter 子類,用於檢索不同種類的資料和構建 AdapterView 的視圖。 兩種最常見的適配器是:ArrayAdapter和SimpleCursorAdapter。

             

2.ListView使用步驟

     1).在布局的XML檔案中,添加如下代碼:

           

<ListView      android:id="@+id/list_view"      android:layout_width="match_parent"      android:layout_height="match_parent" />

   

     2)建立list_item的布局檔案,確定每一個View的樣式。

                

  3).建立一個適配器類。

 

     4).綁定資料到視圖。

 

3.使用執行個體

     1).使用ArrayAdapter

           主layout檔案:

mylistview.xml檔案<?xml version="1.0" encoding="UTF-8"?><LinearLayout    xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    >    <ListView         android:id="@+id/mylistview"        android:layout_width="match_parent"        android:layout_height="match_parent"        >    </ListView></LinearLayout>

          list_item的xml檔案:

list_item.xml檔案<?xml version="1.0" encoding="UTF-8"?><TextView xmlns:android="http://schemas.android.com/apk/res/android"         android:layout_width="match_parent"        android:layout_height="match_parent"        android:textSize="18sp"      ></TextView>

         activity檔案:

        

MyActivity.java檔案public class MyActivity extends Activity{    private ListView listview;    @Override    protected void onCreate(Bundle savedInstanceState) {        // TODO Auto-generated method stub      super.onCreate(savedInstanceState);      setContentView(R.layout.mylistview);      listview = (ListView)findViewById(R.id.mylistview);      String[] str = {"上海","北京","天津","江蘇","河南","西藏","新疆","湖南","湖北"};      List<String> listdata = new ArrayList<String>();      listdata.add("上海");      listdata.add("北京");      listdata.add("天津");      listdata.add("江蘇");      ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,R.layout.list_item,listdata);//listdata和str均可      listview.setAdapter(arrayAdapter);    }        }

 

       2.使用SimpleAdapter

         構造方法:SimpleAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to)

         simpleAdapter可以通過hashmap的方式,每個view可以顯示幾種不同的內容。

        1).主layout檔案和上面相同

        2).list_item的布局檔案

             

<?xml version="1.0" encoding="UTF-8"?><RelativeLayout        xmlns:android="http://schemas.android.com/apk/res/android"        android:layout_width="match_parent"        android:layout_height="match_parent"    > <ImageView      android:id="@+id/iv1"     android:layout_width="30dp"     android:layout_height="30dp"     android:src="@drawable/ic_launcher"         /><TextView         android:id="@+id/tv1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:textSize="18sp"        android:text="wgj"        android:layout_toRightOf="@id/iv1"      ></TextView><TextView     android:id="@+id/tv2"     android:layout_width="wrap_content"     android:layout_height="wrap_content"     android:textSize="18sp"     android:text="19歲"     android:layout_below="@id/tv1"     android:layout_toRightOf="@id/iv1"    ></TextView></RelativeLayout>

      3.activity檔案

         

public class MyActivity extends Activity{    private ListView listview;    @Override    protected void onCreate(Bundle savedInstanceState) {        // TODO Auto-generated method stub      super.onCreate(savedInstanceState);      setContentView(R.layout.mylistview);      listview = (ListView)findViewById(R.id.mylistview);      SimpleAdapter simpleAdapter = new SimpleAdapter(this,putData(),R.layout.list_item,              new String[]{"name","age","pic"},new int[]{R.id.tv1,R.id.tv2,R.id.iv1});      listview.setAdapter(simpleAdapter);    }        public List<Map<String,Object>> putData(){                List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();        Map<String,Object> map1 = new HashMap<String,Object>();        map1.put("name", "張三");        map1.put("age", "19歲");        map1.put("pic", R.drawable.friend);        Map<String,Object> map2 = new HashMap<String,Object>();        map2.put("name", "李四");        map2.put("age", "17歲");        map2.put("pic", R.drawable.ic_launcher);        Map<String,Object> map3 = new HashMap<String,Object>();        map3.put("name", "王五");        map3.put("age", "17歲");        map3.put("pic", R.drawable.ic_launcher);        list.add(map1);        list.add(map2);        list.add(map3);        return list;    }  }

   3.使用BaseAdapter

        最佳化方法 convertView 重用對象

          3.1.通過緩衝convertView實現 
              - 這種利用緩衝contentView的方式可以判斷如果緩衝中不存在View才建立View,如果已經存在可以利用緩衝中的View,提升了效能

          3.2.通過convertView+ViewHolder來實現 
                -ViewHolder就是一個靜態類,使用 ViewHolder 的關鍵好處是緩衝了顯示資料的視圖(View),加快了 UI 的響應速度。 
                -代碼中,當convertView為空白時,用setTag()方法為每個View綁定一個存放控制項的ViewHolder對象。當convertView不為空白,重複利用已經建立的view的時候,使用getTag()方法擷取綁定的ViewHolder對象,這樣就避免了findViewById對控制項的層層查詢,而是快速定位到控制項。

         

         3.3Adapter檔案

public class MyAdapter extends BaseAdapter{    private LayoutInflater mInflater;    private List<Map<String,Object>> list;            public MyAdapter(Context context , List<Map<String,Object>> list){                this.mInflater = LayoutInflater.from(context);        this.list = list;    }            @Override    public int getCount() {        // TODO Auto-generated method stub        return list.size();    }    @Override    public Object getItem(int position) {        // TODO Auto-generated method stub        return list.get(position);    }    @Override    public long getItemId(int position) {        // TODO Auto-generated method stub        return position;    }    @Override    public View getView(int position, View convertView, ViewGroup parent) {        // TODO Auto-generated method stub                ViewHolder holder = null;                if (convertView == null) {                      holder = new ViewHolder();            convertView = mInflater.inflate(R.layout.list_item, null);            holder.name = (TextView)convertView.findViewById(R.id.tv1);            holder.age = (TextView)convertView.findViewById(R.id.tv2);            holder.pic = (ImageView)convertView.findViewById(R.id.iv1);            convertView.setTag(holder);        }else{            holder = (ViewHolder)convertView.getTag();        }                holder.name.setText((String)list.get(position).get("name"));        holder.age.setText((String)list.get(position).get("age"));        holder.pic.setBackgroundResource((Integer)list.get(position).get("pic"));                return convertView;    }            public final class ViewHolder{                public TextView name;        public TextView age;        public ImageView pic;    }}

    3.4  Activity檔案

        

public class MyActivity extends Activity{    private ListView listview;    @Override    protected void onCreate(Bundle savedInstanceState) {        // TODO Auto-generated method stub      super.onCreate(savedInstanceState);      setContentView(R.layout.mylistview);      listview = (ListView)findViewById(R.id.mylistview);      MyAdapter myAdapter = new MyAdapter(this,putData());      listview.setAdapter(myAdapter);    }        public List<Map<String,Object>> putData(){                List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();        Map<String,Object> map1 = new HashMap<String,Object>();        map1.put("name", "張三");        map1.put("age", "19歲");        map1.put("pic", R.drawable.friend);        Map<String,Object> map2 = new HashMap<String,Object>();        map2.put("name", "李四");        map2.put("age", "17歲");        map2.put("pic", R.drawable.ic_launcher);        Map<String,Object> map3 = new HashMap<String,Object>();        map3.put("name", "王五");        map3.put("age", "17歲");        map3.put("pic", R.drawable.ic_launcher);        list.add(map1);        list.add(map2);        list.add(map3);        return list;    }  }

 

4.參考文章

    【1】51442363

    【2】51088239

                

        

安卓ListView的使用

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.