实例2:实现带图标的ListView

1、布局文件

<ListView
        android:id="@+id/listView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

2、编辑用于布局列表项内容的xml布局文件items.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent" android:layout_height="match_parent">
    <ImageView
        android:id="@+id/image"
        android:padding="10px"
        android:paddingTop="20px"
        android:paddingBottom="20px"
        android:adjustViewBounds="true"
        android:maxWidth="72px"
        android:maxHeight="72px"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/title"
        android:padding="10px"
        android:layout_gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

3、在主活动的onCreate()方法中

ListView listView = (ListView)findViewById(R.id.listView1);//获取列表视图
        int[] imageId = new int[]{R.drawable.img01,R.drawable.img02,R.drawable.img03,R.drawable.img04,R.drawable.img05,R.drawable.img06};//定义并初始化保存图片id的数组
        String[] title = new String[]{"项目1","项目2","项目3","项目4","项目5","项目6"};//定义并初始化保存列表项文字的数组
        List<Map<String,Object>> listItems = new ArrayList<Map<String,Object>>();//创建一个List集合
        //通过for循环将图片id和列表项文字放到Map中,并添加到List集合中
        for (int i=0;i<imageId.length;i++){
            Map<String,Object> map = new HashMap<String,Object>();//实例化Map对象
            map.put("image",imageId[i]);
            map.put("title",title[i]);
            listItems.add(map); //将map对象添加到List集合中
        }
        SimpleAdapter adapter = new SimpleAdapter(this,listItems,R.layout.items,new String[]{"title","image"},new int[]{R.id.title,R.id.image});//创建SimpleAdapter
        listView.setAdapter(adapter);


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值