ListView的简单实用

效果图

ListView的简单实用_第1张图片


Java源码

/**
         * 功能:通过数组(图片和字符串),实现带有图标和文字的ListView
         */
        ListView listView = (ListView)findViewById(R.id.listView);
        // 获得数组的图片
        TypedArray image = getResources().obtainTypedArray(R.array.image);
        int[] imageId = new int[image.length()];
        // 获得数组图片对应的Id
        for (int i = 0; i < image.length(); i++)
        {
            imageId[i] = image.getResourceId(i,0);
        }
        // 获得数组的字符串
        String[] title = getResources().getStringArray(R.array.title);

        List<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>();
        // 建立map关联,放进List列表里边
        for (int i = 0; i < imageId.length; i++)
        {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("image", imageId[i]);
            map.put("title", title[i]);
            listItems.add(map);
        }
        // 适配器, 注意 String[] 的用法,它们分别是map的Key;
        SimpleAdapter adapter = new SimpleAdapter(this, listItems, R.layout.list_item,
                new String[]{"image", "title"}, new int[]{R.id.image, R.id.title});
        listView.setAdapter(adapter);

XML数组

<resources>
    <string-array name="image">
        <item>@drawable/img01</item>
        <item>@drawable/img02</item>
        <item>@drawable/img03</item>
        <item>@drawable/img04</item>
        <item>@drawable/img05</item>
        <item>@drawable/img06</item>
        <item>@drawable/img07</item>
        <item>@drawable/img08</item>
    </string-array>
    <string-array name="title">
        <item>保密设置</item>
        <item>安全</item>
        <item>系统设置</item>
        <item>上网</item>
        <item>"我的文档</item>
        <item>GPS导航</item>
        <item>我的音乐</item>
        <item>E-mail</item>
    </string-array>
</resources>

Layout  list_item

<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:paddingRight="10px"
        android:paddingTop="20px"
        android:paddingBottom="20px"
        android:adjustViewBounds="true"
        android:maxWidth="72px"
        android:maxHeight="72px"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10px"
        android:layout_gravity="center"
        android:id="@+id/title"
        />

</LinearLayout>




你可能感兴趣的:(ListView的简单实用)