常用数据适配器 SimpleAdapter

常用数据适配器 SimpleAdapter_第1张图片

MainActivity.java

package com.example.simpleadapter;

import java.io.ObjectOutputStream.PutField;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.SimpleAdapter;


public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ListView lv = (ListView)findViewById(R.id.lv);
        List> data = new ArrayList>();

        Map map1 = new HashMap();
        map1.put("name", "第一关");
        map1.put("icon", R.drawable.ic_menu_home);

        Map map2 = new HashMap();
        map2.put("name", "第二关");
        map2.put("icon", R.drawable.ic_menu_info_details);

        Map map3 = new HashMap();
        map3.put("name", "第三关");
        map3.put("icon", R.drawable.ic_menu_invite);

        Map map4 = new HashMap();
        map4.put("name", "第四关");
        map4.put("icon", R.drawable.ic_menu_login);

        Map map5 = new HashMap();
        map5.put("name", "第五关");
        map5.put("icon", R.drawable.ic_menu_manage);

        data.add(map1);
        data.add(map2);
        data.add(map3);
        data.add(map4);
        data.add(map5);
        //data 绑定的数据   list集合
        //R.layout.list  数据显示对应的布局
        //要让数据跟view对象建立一个映射关系
        //from[]  map集合里面数据的key
        //to[]  布局文件里的id
        lv.setAdapter(new SimpleAdapter(this, data, R.layout.list, new String[]{"name","icon"}, new int[]{R.id.tv,R.id.iv}));
    }
}

res/layout/activity_main.xml

<RelativeLayout 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"
    tools:context="com.example.simpleadapter.MainActivity" >

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

RelativeLayout>

创建xml文件 list.xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#66000000"
    android:orientation="horizontal" >
    <ImageView
        android:id="@+id/iv"
        android:layout_width="wrap_content"
        android:layout_height="match_parent">
    ImageView>
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="match_parent" >
    TextView>


LinearLayout>

你可能感兴趣的:(eclipse)