SimpleAdapter的使用


 1 package org.hjw.simpleadaptertest;
 2 
 3 import java.util.ArrayList;
 4 import java.util.HashMap;
 5 import java.util.List;
 6 import java.util.Map;
 7 
 8 import android.os.Bundle;
 9 import android.app.Activity;
10 import android.app.AlertDialog;
11 import android.view.Menu;
12 import android.view.View;
13 import android.view.View.OnClickListener;
14 import android.widget.AdapterView;
15 import android.widget.AdapterView.OnItemClickListener;
16 import android.widget.ListView;
17 import android.widget.SimpleAdapter;
18 
19 public class MainActivity extends Activity {
20 
21     private String[] names = { "虎頭", "弄玉", "李清照", "李白" };
22     private String[] descs = { "可愛的小孩", "一個很擅長音樂的女孩", "一個很擅長文學的新女性", "浪漫主義詩人" };
23     private int[] imageIds = new int[] { R.drawable.tiger, R.drawable.nongyu,
24             R.drawable.qingzhao, R.drawable.libai };
25     private ListView list;
26     @Override
27     protected void onCreate(Bundle savedInstanceState) {
28         super.onCreate(savedInstanceState);
29         setContentView(R.layout.activity_main);
30 
31         List<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>();
32         for (int i = 0; i < names.length; i++) {
33             Map<String, Object> item = new HashMap<String, Object>();
34             item.put("header", imageIds[i]);
35             item.put("personname", names[i]);
36             item.put("desc", descs[i]);
37             listItems.add(item);
38         }
39 
40         SimpleAdapter simpleAdapter = new SimpleAdapter(this, listItems,
41                 R.layout.frag, new String[] { "header", "personname", "desc" },
42                 new int[] { R.id.header, R.id.name, R.id.desc });
43          list=(ListView)findViewById(R.id.mylist);
44         list.setAdapter(simpleAdapter);
45         list.setOnItemClickListener(new OnItemClickListener() {
46 
47             @Override
48             public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
49                     long arg3) {
50                     new AlertDialog.Builder(MainActivity.this).setMessage("您選中的是:"+names[arg2]).show();
51             }
52         });
53     }
54     
55     @Override
56     public boolean onCreateOptionsMenu(Menu menu) {
57         // Inflate the menu; this adds items to the action bar if it is present.
58         getMenuInflater().inflate(R.menu.main, menu);
59         return true;
60     }
61 
62 }

ps:1.simpleadapter的初始化。

      第一個為上下文,第二個為列表項,第三個為界面布局文件的資源ID,第四個為列表項的Key,第五個為填充的組件.

     2. 列表項資源文件的布局。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM