Android的适配器的学习和使用(整理)

Android的适配器的学习和使用(整理)

 

在开发中我们需要绑定一些数据展现到桌面上,这是就需要AdapterView。AdapterView是ViewGroup的子类,它决定了怎么展现视图通过Adapter来绑定特殊的数据类型。AdapterView是非常有帮助的当你展现数据在你的布局中。Gallery,ListView和Spinner是AdapterView的子类。

简单的adapter的例子:

 
public class SimpleList extendsListActivity { 
    private String[]mListString={"姓名:王魁锋","性别:男","年龄:23", 
           "居住地:上海市普陀区","邮箱:wangkuifeng0118@126.com"}; 
    private ListViewmListView=null; 
    @Override 
    protected voidonCreate(Bundle savedInstanceState) { 
       // TODO Auto-generated method stub 
       super.onCreate(savedInstanceState); 
       mListView=this.getListView(); 
       setListAdapter(new ArrayAdapter<String>(this, 
           android.R.layout.simple_list_item_1,mListString)); 
       mListView.setOnItemClickListener(new OnItemClickListener() { 
 
           @Override 
           public void onItemClick(AdapterView<?> parent, View view, 
                   int position, long id) { 
               // TODO Auto-generated method stub 
           Toast.makeText(SimpleList.this, "你选择了:"+mListString[position],1).show(); 
           } 
       }); 
    } 

  这里用到了系统定义好的适配模式,当然这只能用来简单的数据适配

    接下来看一个稍微复杂点的,SimpleAdapter怎么适配:


public class IconList extendsListActivity { 
 
     privateString[] mListTitle = { "姓名", "性别", "年龄", "居住地","邮箱"};   
       private String[] mListStr = { "王魁锋", "男","23", "上海市普陀区",   
           "wangkuifeng0118@126.com"};   
       ListView mListView = null;   
       ArrayList<Map<String,Object>> mData= newArrayList<Map<String,Object>>();;   
       
       @Override 
       protected void onCreate(Bundle savedInstanceState) { 
           // TODO Auto-generated method stub 
            mListView = getListView();   
                 
           int lengh = mListTitle.length;   
           for(int i =0; i < lengh; i++) {   
               Map<String,Object> item = newHashMap<String,Object>();   
               item.put("image", R.drawable.portrait);   
               item.put("title", mListTitle[i]);   
               item.put("text", mListStr[i]);   
               mData.add(item);    
           }   
           SimpleAdapter adapter = newSimpleAdapter(this,mData,R.layout.iconlist,   
               new String[]{"image","title","text"},newint[]{R.id.image,R.id.title,R.id.text});    
               setListAdapter(adapter);   
           mListView.setOnItemClickListener(new OnItemClickListener() {   
               @Override 
               public void onItemClick(AdapterView<?> parent, View view, 
                       int position, long id) { 
                   // TODO Auto-generated method stub 
                    Toast.makeText(IconList.this,"您选择了标题:" + mListTitle[position] +"   内容:"+mListStr[position],Toast.LENGTH_LONG).show();   
                      
               }   
           });   
           super.onCreate(savedInstanceState); 
       } 
} 


    上面的数据可以是同数据库读取的也可以是从网络获取的,

    如果要做更复杂的布局,哪就要用BaseAdapter了。先看一下布局文件:

 

<?xml version="1.0"encoding="utf-8"?>   
   
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"   
   android:layout_width="fill_parent"android:layout_height="wrap_content">   
    <ImageViewandroid:id="@+id/color_image"   
       android:layout_width="wrap_content"android:layout_height="fill_parent"   
       android:layout_alignParentTop="true"android:layout_alignParentBottom="true"   
       android:adjustViewBounds="true"   
       android:padding="2dip" />   
    <TextViewandroid:id="@+id/color_title"   
       android:layout_width="fill_parent"android:layout_height="wrap_content"   
       android:layout_toRightOf="@+id/color_image"   
       android:layout_alignParentTop="true"   
       android:layout_alignParentRight="true"android:singleLine="true"   
       android:ellipsize="marquee"    
       android:textSize="15dip"  />   
    <TextViewandroid:id="@+id/color_text"   
       android:layout_width="fill_parent"android:layout_height="wrap_content"   
       android:layout_toRightOf="@+id/color_image"   
       android:layout_below="@+id/color_title"   
       android:layout_alignParentBottom="true"   
       android:layout_alignParentRight="true"    
       android:singleLine="true"   
       android:ellipsize="marquee"    
       android:textSize="20dip" />   
</RelativeLayout>   
  

下面是核心代码:

 

public class ColorList extendsListActivity { 
     privateString[] mListTitle = { "姓名", "性别", "年龄", "居住地","邮箱"};   
     privateString[] mListText={"王魁锋","男","23","上海市普陀区","wangkuifeng0118@126.com"}; 
     privateListView mListView=null; 
     privateMyListAdapter myAdapter=null; 
    @Override 
    protected voidonCreate(Bundle savedInstanceState) { 
       // TODO Auto-generated method stub 
        mListView=this.getListView(); 
        myAdapter=new MyListAdapter(this); 
        this.setListAdapter(myAdapter); 
          
        mListView.setOnItemClickListener(new OnItemClickListener() { 
 
           @Override 
           public void onItemClick(AdapterView<?> parent, View view, 
                   int position, long id) { 
               // TODO Auto-generated method stub 
               View v=parent.getChildAt(position); 
               v.setBackgroundColor(Color.RED); 
               Toast.makeText(ColorList.this, "你选择了"+mListText[position],1).show(); 
           } 
       }); 
       super.onCreate(savedInstanceState); 
    } 
    private classMyListAdapter extends BaseAdapter{ 
       private Context mContext; 
       private int[] colors=new int[]{0xff626569,0xff4f5257 }; 
        public MyListAdapter(Context context){ 
            mContext=context; 
        } 
       @Override 
       public int getCount() { 
           // TODO Auto-generated method stub 
           return mListText.length; 
       } 
 
       @Override 
       public Object getItem(int position) { 
           // TODO Auto-generated method stub 
           return position; 
       } 
 
       @Override 
       public long getItemId(int position) { 
           // TODO Auto-generated method stub 
           return position; 
       } 
 
       @Override 
       public View getView(int position, View convertView, ViewGroup parent) { 
           ImageView image=null; 
           TextView title=null; 
           TextView  content=null; 
           if(convertView==null){ 
               convertView=LayoutInflater.from(mContext).inflate(R.layout.colorlist,null); 
               image=(ImageView) convertView.findViewById(R.id.color_image); 
               title=(TextView) convertView.findViewById(R.id.color_title); 
               content=(TextView) convertView.findViewById(R.id.color_text); 
           } 
           int colorPos=position%colors.length; 
           convertView.setBackgroundColor(colors[colorPos]); 
           title.setText(mListTitle[position]); 
           content.setText(mListText[position]); 
           image.setImageResource(R.drawable.portrait); 
             
           return convertView; 
       } 
         
    } 
} 

 

     BaseAdapter可以让我们做比较复杂的布局,只要在xml文件中设置好布局格式,在getView中分别取出放入相应的值就可以了

 

    还有一些SpinnerAdapter和SimpleCursorAdapter等系统自带的适配器,都是比较简单的,可以看下API自行练习一下,这里特别说明一下,从数据库里取出的数据最好直接放入SimpleCursorAdapter很方便的


常用适配器总结

 

一,适配器.        顾名思义,就是把一些数据给弄得适当,适合以便于在View上显示。可以看作是
界面数据绑定的一种理解。它所操纵的数据一般都是一些比较复杂的数据,如数组,链表,数据库,集合等。适配器就像显示器,把复杂的东西按人可以接受的方式来展现。那么适配器是怎么处理得到的数据,并把它显示出来的呢。其实很简单,说白了适配器它也是一个类,在类里面它实现了父类的这几个方法:

publicint getCount() //
得到数据的行数
public Object getItem(int position)//根据position得到某一行的记录
public long getItemId(int position)//得到某一条记录的ID

//下面这个方法是最重要的相比于其它几个方法,它显式的定义了,适配器将要以什么样的方式去显示我们所填充的数据,在自定义的适配器里面我们通常会给它写个布局文件

publicView getView(int position, ViewconvertView, ViewGroup parent)  

我们常用的适配器一共有三个,当然不包含自定义的适配器,哪三个那就是ArrayAdapter,SimpleAdapter,SimpleCursorAdapter这三个,他们都是继承BaseAdapter
其中以ArrayAdapter最为简单,只能展示一行字。SimpleAdapter有最好的扩充性,可以自定义出各种效果。SimpleCursorAdapter可以认为是SimpleAdapter对数据库的简单结合,可以方面的把数据库的内容以列表的形式展示出来。

二,一般对于前两个适配器,他们的数据来源无非就是String[]或者List。下面我们列举两个例一子:例一,数组作为数据源,填充的是ArrayAdapter    public class Example extends ListActivity{
      String[] sex = new String(){"
男",“女”}//数据源
      ArrayAdapter<String>  adapter;//数组适配器,用的是泛型
      public voidonCreate(Bundle SavedInstanceState){
               super.onCreate(SavedInstanceStat);
                //
在对适配器初始化的时候,顺便把数据源装载到适配器里,                                      //this.android.R.Layout.Simple_List_Item_1这句话
                  //的意思是将数据源以系统定义好的样式放到适配器里.            

               adapter=newArrayAdapter<String(this.android.R.Layout.Simple_List_Item_1,sex);
                  this.setAdapter(adapter);//
这是一个控件类,所以可以直接将适配器绑定到本身对象中。
                       }
                }



            
例二:List作为数据源,填充的是SimpleAdapter
                       ListView list =(ListView)findViewById(R.id.MyListView);        
                      //
生成动态数组,并且转载数据
                     ArrayList<HashMap<String, String>> mylist =newArrayList<HashMap<String, String>>();
                     for(int i=0;i<30;i++)
                             {
                                     HashMap<String, String>map = new HashMap<String,String>();
                                     map.put("ItemTitle","This isTitle.....");
                                     map.put("ItemText","This is text.....");

                            mylist.add(map);

                           }
                   //
生成适配器,数组===》ListItem
                     SimpleAdapter mSchedule = new SimpleAdapter(this, //
没什么解释 mylist,//数据来源     R.layout.my_listitem,//ListItem的XML实现 //动态数组与ListItem对应的子项          

                     new   String[]{"ItemTitle","ItemText"}, //ListItem
的XML文件里面的两个TextViewID  new int[] {R.id.ItemTitle,R.id.ItemText});
                    //
添加并且显示
                     list.setAdapter(mSchedule);
                   }

三,应该说着两个例子都不难,都是一些我们经常见到的用法,那么对于SimpleCursorAdapter又是怎么用的呢,SimpleCursorAdapter一般主要用于数据库,它的数据来源一般都是数据库查询得到的Cursor我们来看下面的例子:
                   String uriString = “content://contacts/people/”;
                    Cursor myCursor =managedQuery(Uri.parse(uriString), null,null, null, null);

         String[] fromColumns = new String[]{People.NUMBER, People.NAME};

                   int[] toLayoutIDs =new int[] {R.id.nameTextView, R.id.numberTextView};
                  SimpleCursorAdapter myAdapter;
                  myAdapter=newSimpleCursorAdapter(this,R.layout.simplecursorlayout,myCursor,fromColumns,
                  toLayoutIDs);//
传入当前的上下文、一个layout资源,一个游标和两个数组:一个包含使用的列   
                  //
的名字,另一个(相同大小)数组包含View中的资源ID,用于显示相应列的数
                  
据值。

                  myListView.setAdapter(myAdapter);
我们把一个游标绑定到了ListView上,并使用自定义的layout显示来显示每一个Item。


四,下面我们来定义自己的适配器。
             为什么要定义自己的适配器呢,原因就在于,当我们想用一些其它的展现方式,或者是我们需要的,呈现方式,这是就得DIY了。
首先我们定义一个类让它继承自BaseAdapter,再让它实现一里面所说的那几个方法。那么这个自定义适配器就算好了。里面的一些方法我在上面都介绍过了,在这就不在赘述了。
                        public class ImageAdapter extendsBaseAdapter {
                                      private Context mcontext;                                               };
                                     //
构造函数里面有两个参数,一个是数据的来源,另一个是上下文。
                        public ImageAdapter(Integer[] imgIds,Contextc){
                                      mcontext=c;
                                      imageIds=imgIds;
                                               }
                        publicint getCount() {
                                // TODOAuto-generated method stub
                               returnimageIds.length;
                                              }

                         publicObject getItem(int position){
                                 // TODO Auto-generated method stub
                                 returnnull;
                                              }

                         publiclong getItemId(int position){
                                // TODOAuto-generated method stub
                               returnposition;
                                }

                          //
主要工作是做在这里,可以自定义布局,在这里我就不多说了
                        publicView getView(int position, ViewconvertView, ViewGroup parent) {
                           // TODO Auto-generated methodstub
                                   ImageView imageview = newImageView(mcontext);
                                   imageview.setImageResource(imageIds[position]);
                                    imageview.setLayoutParams(newGallery.LayoutParams(120,120));
                                    imageview.setScaleType(ImageView.ScaleType.FIT_CENTER);
                                    return imageview;
                                 }
                 }

 

 

转载自:]http://www.cnblogs.com/transmuse/archive/2010/11/26/1889194.html

Android中有很多的适配器,首先看看这些适配器的继承结构

这些适配器中,BaseAdapter用的最多,也用的最熟,先放过他,从ArrayAdapter开始

1. ArrayAdapter

public class ArrayAdapter extendsBaseAdapterimplementsFilterable

ClassOverview

A ListAdapter that manages a ListView backed by an array of arbitrary(任意的)objects. By default this class expects that the provided resource id referencesa single TextView. If you want to use a more complex layout, use theconstructors that also takes a field id. That field id should reference aTextView in the larger layout resource. However the TextView is referenced, itwill be filled with the toString() of each object in the array. You can addlists or arrays of custom objects. Override the toString() method of yourobjects to determine (确定)what text will be displayed for theitem in the list. To use something other than TextViews for the array display,for instance, ImageViews, or to have some of data besides toString() resultsfill the views, overridegetView(int,View, ViewGroup) to return the type of view you want.

一个listAdapter用来管理一个用一组任意对象的数组填充的ListView。默认的ListAdapter希望提供的ListView每一项的xml布局配置文件中只有一个TextView,如果你想使用一个符合布局的话,你就要使用含有id字段的构造函数了,这个id要去引用这个复杂布局文件中的一个TextViewTextView被引用了,使用数组中的对象,调用toString方法,转换成字符串来填充这个TextView,你可以使用包含自定义对象的数组或者集合。重写自定义对象的toString()方法,来保证ListView显示。你也可以是使用其他的一些非TextView控件来显示数组中的数据,例如ImageViews,通过重写AdaptergetView方法来得到你想要的view

构造函数:

public ArrayAdapter (Context context, int textViewResourceId)

context  The current context.当期的上下文对象

textViewResourceId  The resource ID for a layout filecontaining a TextView to use when instantiating views.一个包含了TextView的布局xml文件的id,注意(这个布局文件里只能有TextView一个控件,TextView不能有父控件,否则会报错java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be aTextView

类似于这种的xml

<?xml version="1.0" encoding="utf-8"?>
<TextView android:id="@+id/subject"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"android:layout_height="wrap_content"
    android:layout_marginTop="5dip"android:textAppearance="?android:attr/textAppearanceMedium"
    android:singleLine="true"android:ellipsize="end" />

public ArrayAdapter (Context context, int textViewResourceId, T[]objects)

objects:用来填充ListView,给ArrayAdapter提供数据的数组

public ArrayAdapter (Context context, int textViewResourceId, List<T> objects) //建议使用这个,直接给ArrayAdapter填充了数据

//*************************************************************************************************

public ArrayAdapter (Context context, int resource, inttextViewResourceId)

这个是用来复杂布局的,ListViewItem项的布局文件中不止含有一个TextView控件

resource The resource ID for a layout file containing a layout to use wheninstantiating views. ListViewItem项的复杂布局xml文件

textViewResourceIdThe id of the TextView within the layoutresource to be populated(显示) ListViewItem项的复杂布局xml文件中用来显示ArrayAdapter中数据的那个TextView

public ArrayAdapter (Context context, int resource, inttextViewResourceId, T[] objects)

public ArrayAdapter (Context context, int resource, inttextViewResourceId, List<T> objects)//建议使用这个,直接给ArrayAdapter填充了数据

方法:

public staticArrayAdapter<CharSequence> createFromResource (Context context, int textArrayResId, inttextViewResId)

Creates a new ArrayAdapter from external resources. The content of thearray is obtained throughgetTextArray(int).Parameters这个方法能够使用数组xml文件中配置的数据来创建一个ArrayAdapter,这个数组中的内容如何获得,通过this.getResources().getTextArray(id)方法获得。

           textArrayResIdThe identifier of the array to use as the data source.自定义数组xml文件的标识id号,也就是ArrayAdapter要绑定到ListVIew中的数据

           textViewResIdThe identifier of the layout used to create views.//用于显示数组数据的布局文件的id标识号(注意:该布局文件中只能有一个TextView,有多个就会报错,一般是ClassCastException)

public View getDropDownView (int position,View convertView,ViewGroup parent)

Get a View that displays in the drop down popupthe data at the specified position in the data set.

positionindex of the item whose view we want.

convertViewthe old view to reuse, if possible. Note: You should check that this viewis non-null and of an appropriate type before using. If it is not possible toconvert this view to display the correct data, this method can create a newview.

parentthe parent that this view will eventually be attached to

Returns

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值