常用数据适配器SimpleAdapter

xiaoxiao2021-02-28  112

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<Map<String, Object>> data = new ArrayList<Map<String, Object>>(); Map<String, Object> map1 = new HashMap<String, Object>(); map1.put("name", "第一关"); map1.put("icon", R.drawable.ic_menu_home); Map<String, Object> map2 = new HashMap<String, Object>(); map2.put("name", "第二关"); map2.put("icon", R.drawable.ic_menu_info_details); Map<String, Object> map3 = new HashMap<String, Object>(); map3.put("name", "第三关"); map3.put("icon", R.drawable.ic_menu_invite); Map<String, Object> map4 = new HashMap<String, Object>(); map4.put("name", "第四关"); map4.put("icon", R.drawable.ic_menu_login); Map<String, Object> map5 = new HashMap<String, Object>(); 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

<?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: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>
转载请注明原文地址: https://www.6miu.com/read-34291.html

最新回复(0)