Android Adapter詳解

Android Adapter 是將數據綁定到UI 界面上的橋接類。 Adapter負責創建和顯示每個項目的子View和提供對下層數據的訪問。支持Adapter綁定的UI控件必須擴展Adapter View抽象類。創建自己的繼承自AdapterView的控件和創建新的Adapter類來綁定它們是可能的。

Android 系統本身提供瞭兩種現成的Adapter 供我們使用。

1.ArrayAdapter:它是一個綁定View到一組對象的通用類。默認情況下,ArrayAdapter綁定每個對象的toString值到layout中預先定義的TextView空間上。構造函數允許用戶使用更加復雜的Layout或者通過重寫getView方法來擴展類從而使用TextView的替代物

2.SimpleCursorAdapter:它綁定View到Content Provider 查詢返回的遊標上。指定一個XML layout定義,然後將數據集的每一列的值綁定到layout中的一個View

 

寫自己的Adapter類實現更多復雜的UI界面和數據綁定

   
public class MyAdapter extends SimpleAdapter {
   
      private LayoutInflater mInflater;
      private Context context;
      private List<Map<String,Object>> list;
      private int resource;
      private String[] tags;
      private int[] ids;
      public MyAdapter(Context context, List<Map<String,Object>> items, int resource,
              String[] tags,int[] ids) {
          super(context, items, resource, tags, ids);
         
          this.mInflater = LayoutInflater.from(context);
          this.context = context;
          this.list = items;
          this.resource = resource;
          this.tags = tags;
          this.ids = ids;
      }
     
      public int getCount() {
          return list.size();
      }
     
      public Object getItem(int position) {
          return list.get(position);
      }
     
      public long getItemId(int position) {
          return position;
      }
     
      public View getView(final int position, View convertView, ViewGroup parent) {
          convertView = super.getView(position, convertView, parent);
          if (convertView == null) { 
              Toast.makeText(context, "this is null", 2000).show();
            
        
          } else {  
             
          }
        
          ImageView more = (ImageView) convertView.findViewById(R.id.iv_more);
         
          more.setOnClickListener(new View.OnClickListener() {
              public void onClick(View arg0) {
                  Intent intent = new Intent(context, VehicleInfoActivity.class);
                  intent.putExtra("vehicleID", VehicleListActivity.idList.get(position));
                  intent.putExtra("CameraID", "0");
                  Toast.makeText(context, "sssssss", 2000).show(); 
                  context.startActivity(intent);
                 
     
              }
          });
         
          return convertView;
      }
}

作者:gps夢想

發佈留言