Android_Spinner_SimpleAdapter

时间:2024-08-24 23:36:38

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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" > <Spinner
android:id="@+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"/> </RelativeLayout>

适配器显示布局文件:

<?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/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/> </LinearLayout>

源代码:

package com.example.day04_simpleadapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.SimpleAdapter;
import android.widget.Spinner; public class MainActivity extends Activity { private Spinner spinner;
private String[] city;
private int[] pic; /* SimpleAdapter:
arraydapter 只能显示单个文本(太单一)
SimpleAdapter 可以放置复杂样式的条目
SimpleAdapter <List<Map<String,Object>>> adapter = new SimpleAdapter<>(
Context context,// 上下文对象
List<? extends Map<String, ?>> data,// 表示的是数据 ,适配控件的的每一条数据用list装, 数据用map去表示 map中的key与from参数对应
int resource, // 一条数据(一个条目)显示的布局
String[] from,// 与map中的多个key对应
int[] to,// 是需要显示数据的控件的id,该id的顺序必须与from中的key对应(即key获取的值要放到id对应的控件上)
);
*/ @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (Spinner) findViewById(R.id.spinner);
city = new String[] {"北京","上海","杭州","深圳","广州"};
pic = new int[] {R.drawable.ic_launcher,R.drawable.ic_launcher,R.drawable.ic_launcher,R.drawable.ic_launcher,R.drawable.ic_launcher}; SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, getdata(), R.layout.layout01, new String[]{"city","pic"},new int[]{R.id.text,R.id.image});
spinner.setAdapter(adapter);
} private List<? extends Map<String, ?>> getdata() {
// TODO Auto-generated method stub
List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
Map<String,Object>map = null;
for (int i = 0; i < city.length; i++) {
map = new HashMap<String, Object>();
map.put("city",city[i]);
map.put("pic", pic[i]);
list.add(map);
}
return list;
} }