Adapter详解

动态添加数据适配器adapter

Adapter是适配器,许多UI组件需要搭配Adapter来显示界面,例如Spinner与ListView,另外当我们需要动态的添加数据给UI组件时就需要Adapter了。

我们来介绍几个常见的Adapter:

 

ArrayAdapter<T>(comman)
SimpleAdapter extends Baseadapter(comman)
******************************************************************************

这两个适配器非常常见,也非常有用,通常传输的数据可以是ArrayList<>封装的数据。

示例如下:ArrayAdapter

[java][/java]

  1. private String[] string={“china”,”america”,”japan”};
  2. List list=new ArrayList<String>();
  3. for(int i=0;i<string.length;i++)
  4. {
  5. list.add(string[i]);
  6. }
  7. ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,R.layout.simple_spinner_item,list);

首先我们定义封装数据,然后再定义Adapter,最后调用setAdapter()方法。

 

ArrayAdapter有三个参数,第一个参数为Activity.this,第三个参数为动态添加给adapter的数据
对于第二个数据:
R.layout.simple_spinner_item:意思是将数据传给一个简单地TextView组件

示例:SimpleAdapter

 

[java][/java] 

  1. public class SimpleAdapter extends Activity{
  2. private String[] names =new String[]{“nick”,”lebron”,”kobe”,”kevin”};
  3. private int[] imgsIds[] =new Int[] {R.drawable.1,R.drawable.2,R.drawable.3,R.drawable.4};
  4. @Override
  5. public void onCreate(Bundle savedInsatnceState)
  6. {
  7. super.onCreate(savedInsatnceState);
  8. setTitle(“simpleadapter”);
  9. setContentView(R.layout.main);
  10. List<Map><String,Object> list=new ArrayList<Map><String,Object>();//创建动态数组ArrayList
  11. for(int i=0;i<names.length;i++){
  12. Map<String,Object> map=new HashMap=<String,Object>;
  13. map.put(“name”,names[i]);
  14. map.put(“headerImg”,imgsIds[i]);
  15. list.add(map);
  16. }
  17. SimpleAdapter adapter=new SimpleAdaper(this,list,R.layout.main,new String[]{“name”,”headerImg”},new int[]{R.id.name,R.id.headerImg});
  18. ListView list=(ListView)findViewById(R.id.mylist);
  19. list.setAdaper(adapter);
  20. }
  21. }

 
接下来我们介绍另一个常用的Adapter:BaseAdapter
BaseAdapter implements SpinnerAdapter implements ListViewAdapter(可用于ListView和Spinner)

示例:

 

[java][/java]
  1. public MyListView extensds Activity{
  2. @Override
  3. public void onCreate(Bundle savedInstanceState)
  4. {
  5. super.onCreate(savedInsatnceState);
  6. mDate=getDate();
  7. MyAdapter myadapter=new MyAdapter(this);
  8. ListView list=(ListView)findById(R.id.myList);
  9. setAdapter(myadapter);
  10. }
  11.  private List<Map<String, Object>> getData() {
  12.             List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
  13.             Map<String, Object> map = new HashMap<String, Object>();
  14.             map.put(“title”, “G1”);
  15.             map.put(“info”, “google 1”);
  16.             map.put(“img”, R.drawable.i1);
  17.             list.add(map);
  18.      //添加第二个Map数据
  19.             map = new HashMap<String, Object>();
  20.             map.put(“title”, “G2”);
  21.             map.put(“info”, “google 2”);
  22.             map.put(“img”, R.drawable.i2);
  23.             list.add(map);
  24.      //添加第三个Map数据
  25.             map = new HashMap<String, Object>();
  26.             map.put(“title”, “G3”);
  27.             map.put(“info”, “google 3”);
  28.             map.put(“img”, R.drawable.i3);
  29.             list.add(map);
  30.         return list; //返回List数据
  31.     }
  32. @verride
  33. protected void onListItemClicked(ListView 1,View v,int position,long id){
  34. Log.v(“MyListView4_click”,(String)mData.get(position).get(“title”));
  35.     }
  36. public void showInfo(){
  37.     new AlertDiolog.Builder(this)
  38.     .setTitle(“MyListView”)
  39.     .setMessage(Introduce)
  40.     .setPositiveButton(“Ensure”,new DialogInterface.OnClickListener()
  41.     {@Override
  42.     public void onClick(DialogInterface dialog,int which){} }).show();
  43.     }
  44. }
  45. private final class ViewHolder{
  46. public ImageView img;
  47. public TextView title;
  48. public TextView info;
  49. public Button viewBu;
  50. }
  51. public class MyAdapter extens BaseAdapter{
  52. private LayoutInlfater myInflater;
  53. public MyAdapter(Context context){
  54. this.myInflater=LayoutInflater.from(context);
  55. }
  56. @Override
  57. public int getCount(){
  58.     return mDate.size();}
  59. @Override
  60. public long getItemId(int position){
  61.     return null;}
  62. @Override
  63. public Object getItmeId(int position){
  64.     return 0;}
  65. @Override
  66. public View getview(int position,View convertView,ViewGroup parent){
  67. ViewHolder holder=null;
  68. if(convertView==null){
  69. holder=new ViewHolder();
  70. convertView=mInflater.inflate(R.layout.list,null)
  71. //inflate函数有两个参数–解析界面布局
  72. holder.img=(ImageView)convertView.findViewById(R.id.img);
  73. holder.title=(TextView)convertView.findViewById(R.id.title);
  74. holder.info=(TextView)convertView.findViewById(R.id.info);
  75. holder.viewBu=(TextView)convertView.indViewById(R.id.viewBu);
  76. convertView.setTag(holder);
  77.     }else{holder=(ViewHolder)convertViewgetTag();}
  78. holder.img.setBackgroundResounce((Integer)mDate.get(position).get(“img”));
  79. holder.title.setText((String)mdata.get(position).get(“title”));
  80. holder.info.setText((String)mData.get(position).get(“info”));
  81. holder.viewBu.setOnClickListener(new View.OnClickListener(){
  82.     @Override
  83.     public void onClick(View v){
  84.     showInfo(); }
  85.     });
  86. return convertView;
  87. }
  88. }
  89. }

getView()方法有三个参数,int position表示第几行,第几个Item;convertView 表示解析过来的布局,getCount表示列表项的个数。

 

 

在使用ExpandabListView组件时,我们必须使用这个Adapter:

ExpandableAdapter:(用于ExpandableListView):

 

[java][/java]

  1. public class ExpandableListViewTest extends Activity
  2. {
  3.     @Override
  4.     public void onCreate(Bundle savedInstanceState)
  5.     {
  6.         super.onCreate(savedInstanceState);
  7.         setContentView(R.layout.main);
  8.         //创建一个BaseExpandableListAdapter对象
  9.         ExpandableListAdapter adapter = new BaseExpandableListAdapter()
  10.         {
  11.             int[] logos = new int[]
  12.             {
  13.                 R.drawable.p,
  14.                 R.drawable.z,
  15.                 R.drawable.t
  16.             };
  17.             private String[] armTypes = new String[]
  18.                 { “神族兵种”, “虫族兵种”, “人族兵种”};
  19.             private String[][] arms = new String[][]
  20.             {
  21.                 { “狂战士”, “龙骑士”, “黑暗圣堂”, “电兵” },
  22.                 { “小狗”, “刺蛇”, “飞龙”, “自爆飞机” },
  23.                 { “机枪兵”, “护士MM” , “幽灵” }
  24.             };
  25.             //获取指定组位置、指定子列表项处的子列表项数据
  26.             @Override
  27.             public Object getChild(int groupPosition, int childPosition)
  28.             {
  29.                 return arms[groupPosition][childPosition];
  30.             }
  31.             @Override
  32.             public long getChildId(int groupPosition, int childPosition)
  33.             {
  34.                 return childPosition;
  35.             }
  36.             @Override
  37.             public int getChildrenCount(int groupPosition)
  38.             {
  39.                 return arms[groupPosition].length;
  40.             }
  41.             private TextView getTextView()
  42.             {
  43.                 AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
  44.                         ViewGroup.LayoutParams.FILL_PARENT, 64);
  45.                 TextView textView = new TextView(ExpandableListViewTest.this);
  46.                 textView.setLayoutParams(lp);
  47.                 textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
  48.                 textView.setPadding(36, 0, 0, 0);
  49.                 textView.setTextSize(20);
  50.                 return textView;
  51.             }
  52.             //该方法决定每个子选项的外观
  53.             @Override
  54.             public View getChildView(int groupPosition, int childPosition,
  55.                     boolean isLastChild, View convertView, ViewGroup parent)
  56.             {
  57.                 TextView textView = getTextView();
  58.                 textView.setText(getChild(groupPosition, childPosition).toString());
  59.                 return textView;
  60.             }
  61.             //获取指定组位置处的组数据
  62.             @Override
  63.             public Object getGroup(int groupPosition)
  64.             {
  65.                 return armTypes[groupPosition];
  66.             }
  67.             @Override
  68.             public int getGroupCount()
  69.             {
  70.                 return armTypes.length;
  71.             }
  72.             @Override
  73.             public long getGroupId(int groupPosition)
  74.             {
  75.                 return groupPosition;
  76.             }
  77.             //该方法决定每个组选项的外观
  78.             @Override
  79.             public View getGroupView(int groupPosition, boolean isExpanded,
  80.                     View convertView, ViewGroup parent)
  81.             {
  82.                 LinearLayout ll = new LinearLayout(ExpandableListViewTest.this);
  83.                 ll.setOrientation(0);
  84.                 ImageView logo = new ImageView(ExpandableListViewTest.this);
  85.                 logo.setImageResource(logos[groupPosition]);
  86.                 ll.addView(logo);
  87.                 TextView textView = getTextView();
  88.                 textView.setText(getGroup(groupPosition).toString());
  89.                 ll.addView(textView);
  90.                 return ll;
  91.             }
  92.             @Override
  93.             public boolean isChildSelectable(int groupPosition, int childPosition)
  94.             {
  95.                 return true;
  96.             }
  97.             @Override
  98.             public boolean hasStableIds()
  99.             {
  100.                 return true;
  101.             }
  102.         };
  103.         ExpandableListView expandListView = (ExpandableListView)
  104.             findViewById(R.id.list);
  105.         expandListView.setAdapter(adapter);
  106.     }
  107. }

 

 

还有一些Adapter,例如:

SimpleCursorAdapter(用于来自数据库的数据)

关键代码如下:
Cursor cur = getContentResolver().query(People.CONTENT_URI, null, null, null, null);
startManagingCursor(cur);
//来自系统通讯录数据库的Cursor数据
ListAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cur, new String[] {People.NAME}, new int[] {android.R.id.text1});
setListAdapter(adapter);

标签