适配器之SimpleAdapter

来源:互联网 发布:阿里云logo矢量 编辑:程序博客网 时间:2024/06/05 05:33

     android里的适配器,刚开始看起来,我觉得很神奇,而且有种桃花渐欲迷人眼之感。它说白了,就是把两个不匹配的东西,连接起来,让它们能发挥作用。不匹配的东西种类多了,那自然适配器的种类也会很多。下面先介绍一种SimpleAdapter 的适配器。demo的作用是把一组图片和文字内容,放到一个下拉列表里显示出来。

     MyAdapter.java 这个文件当相于数据源

    

public class MyAdapter {public MyAdapter() {// TODO Auto-generated constructor stub}public static List<Map<String,Object>> getListMaps(){List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();Map<String,Object> map1 = new HashMap<String, Object>();map1.put("Logo", R.drawable.calendar);map1.put("applicationName", "日历");Map<String,Object> map2 = new HashMap<String, Object>();map2.put("Logo", R.drawable.eoemarket);map2.put("applicationName", "eoemarket客户端");list.add(map1);list.add(map2);return list;}}
MainActivity.java 主要的Actity程序

public class MainActivity extends ActionBarActivity {private Spinner spinner;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);spinner = (Spinner) this.findViewById(R.id.spinner);List<Map<String,Object>> listmaps = MyAdapter.getListMaps();//这是适配器的关键所在,SimpleAdapter simpleAdapter = new SimpleAdapter(MainActivity.this, listmaps,R.layout.item, new String[] { "Logo", "applicationName" },new int[] { R.id.imageview, R.id.textview });spinner.setAdapter(simpleAdapter);spinner.setOnItemSelectedListener(new OnItemSelectedListener() {@Overridepublic void onItemSelected(AdapterView<?> parent, View view,int position, long id) {// TODO Auto-generated method stubString appName =((Map<String,Object>)spinner.getItemAtPosition(position)).get("applicationName").toString();setTitle(appName);}@Overridepublic void onNothingSelected(AdapterView<?> arg0) {// TODO Auto-generated method stub}});
activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical"    >      <Spinner android:id="@+id/spinner"        android:layout_width="fill_parent"    android:layout_height="wrap_content"/></LinearLayout>

item.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="wrap_content"    android:orientation="horizontal" >    <ImageView        android:id="@+id/imageview"        android:layout_width="60dp"        android:layout_height="60dp"         android:src="@drawable/icon"        android:paddingLeft="10dp"/>    <TextView android:id="@+id/textview"        android:textColor="#000"        android:textSize="16dp"        android:layout_width="wrap_content"        android:layout_height="fill_parent"         android:gravity="center_vertical"        android:paddingLeft="10dp"/>    </LinearLayout>
效果图如下:


源代码下载地址:http://download.csdn.net/detail/chexitianxia/9115001

0 0
原创粉丝点击