androidUI第四部分---1.4.2ListView用法—利用SimpleAdapter生成ListView

利用simpleAdapter关联ListView时由于参数较多显得较为复杂,代码如下:

setContentView(R.layout.main);

      ListView lv = (ListView)this.findViewById(R.id.listview);//第一步

////第二步生成simpleAdapter     

ArrayList<HashMap<String, Object>> al = new ArrayList<HashMap<String, Object>>(); 

      for(int i=0;i<7;i++)

      {

        HashMap<String,Object> hm =new HashMap<String,Object>();

        hm.put("imgview", R.drawable.icon);

        hm.put("textItem", "textitem"+i);

        al.add(hm);

      }

      SimpleAdapter sa = new SimpleAdapter(this,al,R.layout.listviewitem,new String[]{"imgview","textItem"},new int[]{R.id.imgview,R.id.text});

//第三步关联simpleAdapterlistview

      lv.setAdapter(sa);

重点讲下第二步生成simpleAdapter对象时需要五个参数,第一个为context,第二个为一个list of map,即为一个list里面每个元素为map这里呢可以用ArrayList<HashMap<String,Object>>的对象,HashMap里面存放的Object即为我们要显示在listview上的东东,第三参数为listview每个item的布局文件,第四个参数为查询hashmap里面的Object值时的key,第五个参数为listviewitem的布局文件中对应的控件的id

Main.xml如下

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:orientation ="horizontal"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    >

  <ListView

  android:layout_width ="fill_parent"

  android:layout_height="wrap_content"

  android:id="@+id/listview"

  ></ListView>

  

</RelativeLayout>

listviewitem.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

> 

<TextView  

      android:layout_width="wrap_content"   

    android:layout_height="wrap_content"   

    android:id="@+id/text"

> 

</TextView>

 

 <ImageView

android:id="@+id/imgview"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

> 

</ImageView>

</LinearLayout>

你可能感兴趣的:(androidUI第四部分---1.4.2ListView用法—利用SimpleAdapter生成ListView)