您的位置:首页 > 移动开发 > Android开发

Android之SimpleAdapter的使用

2015-10-13 17:56 399 查看

Android之SimpleAdapter的使用

运行效果:



MainActivity.java

[code]package com.example.chatdemo;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import java.util.*;

public class MainActivity extends Activity {

    private ListView listView = null;

    private List<Map<String, String>> list = new ArrayList<Map<String, String>>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView) findViewById(R.id.list_view);
        setData();
        listView.setAdapter(getAdapter());
    }

    private void setData() {
        int[] image = { R.drawable.apple_pic, R.drawable.banana_pic,
                R.drawable.cherry_pic, R.drawable.grape_pic,
                R.drawable.mango_pic, R.drawable.strawberry_pic,
                R.drawable.watermelon_pic };
        String[] data = { "苹果", "香蕉", "橙子", "西瓜", "椰子", "梨子", "榴莲" };

        for (int i = 0; i < image.length; i++) {
            Map<String, String> map = new HashMap<String, String>();
            map.put("img", String.valueOf(image[i]));
            map.put("text", data[i]);
            list.add(map);
        }
    }

    private SimpleAdapter getAdapter() {

        SimpleAdapter adpater = new SimpleAdapter(this, list,
                R.layout.item_layout, new String[] { "img", "text" },
                new int[] { R.id.img, R.id.tv });

        return adpater;
    }

}


activity_main.xml

[code]<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

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

</LinearLayout>


item_layout.xml

[code]<?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"
    android:orientation="horizontal" >

    <ImageView
        android:id="@+id/img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center" />

    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center" 
        android:layout_gravity="center"/>

</LinearLayout>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: