欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android 适配器模式应用及设计原理

程序员文章站 2024-03-05 12:54:36
适配器模式是一种重要的设计模式,在 android 中得到了广泛的应用。适配器类似于现实世界里面的插头,通过适配器,我们可以将分属于不同类的两种不同类型的数据整合起来,而不...

适配器模式是一种重要的设计模式,在 android 中得到了广泛的应用。适配器类似于现实世界里面的插头,通过适配器,我们可以将分属于不同类的两种不同类型的数据整合起来,而不必去根据某一需要增加或者修改类里面的方法。

适配器又分为单向适配器和双向适配器,在 android 中前者使用的比较频繁。比较常见的实现方式是:首先定义一个适配类,内部定义一个私有的需要适配的对象,该类提供一个构造函数,将该对象的一个实例作为参数传入,并在构造函数里面进行初始化,再提供一个公有的方法,返回另外一个需要适配的类所需要的数据类型。这样通过创建一个额外的类,专门负责数据类型的转换,在不改动原有类的前提下实现了所需的功能。这种设计模式提供了更好的复用性和可扩展性,尤其在我们无法获修改其中一个类或者类与类之间有比较多的不同类型的数据需要进行适配的时候显得格外重要。

在 android 中常见的适配器类有: baseadapter 、 simpleadapter 等

初识android时,我对listview、gradview中的adapter一直半懂非懂,每次写adapter都觉得异常痛苦,故而有了此文,希望能帮到一些初学者。

先来看下适配器模式的官方解释,将一个类的接口转换成客户希望的另外一个接口,adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。乍看肯定不知所云,通俗说下我个人的理解:当我们创建一个view之后,肯定要接着规定该view的大小、位置、显示的内容信息、触摸事件的回调等等,我们发现将这些东西放一起导致代码太耦合甚至冗余了,这时候就可以使用adapter模式,将这个流程分开,首先我们只管创建一个view,至于该view的内容样式我们完全不用关心,交给我们的小弟adapter去做(前提是这个人是我们的小弟,和我们的view能联系起来),当小弟完成了我们分配给他的任务后(安排子view的样式,信息的解析显示,event回调等),我们只需通过setadapter()将他的工作内容窃取过来就行。

或者再直观点说,我们要买回来了一部iphone7,我们只需要轻松愉快地用它来听歌,看电影,聊微信,至于当他没电了怎么办?如何使用110v、220v电压充电?怎么使用二孔、三孔插头?如何快充如何慢充?这些都不需要我们关心,交给我们的充电器(adapter)即可,我们要做的只需连上usb线和找到插座(setadapter)就行了。

当你不清楚适配的具体流程时,写adapter是非常痛苦的,接下来我们就举栗子详细分析一个完整的适配器模式工作流程(现在除了我的奇葩公司,应该没人会用listview了吧,所以这里直接以recyclerview为栗,其实listview的adapter也是一样的原理)。

1.创建一个recyclerview并实例化它,然后等着我们的小弟(adapter)完成剩下来的体力活。

 <android.support.v7.widget.recyclerview
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:id="@+id/mrecycler"/>
  
  recyclerview mrecycler= (recyclerview) findviewbyid(r.id.mrecycler);
   mrecycler.setlayoutmanager(new staggeredgridlayoutmanager(2,staggeredgridlayoutmanager.vertical));

2.adapter使用,我们先从源码了解每个方法的回调周期。

public static abstract class adapter<vh extends viewholder> {

 private final adapterdataobservable mobservable = new adapterdataobservable();

 public abstract vh oncreateviewholder(viewgroup parent, int viewtype);

 public abstract void onbindviewholder(vh holder, int position);

 public void onbindviewholder(vh holder, int position, list<object> payloads) {
   onbindviewholder(holder, position);
 }

 /**
  * this method calls {@link #oncreateviewholder(viewgroup, int)} to create a new
  * {@link viewholder} and initializes some private fields to be used by recyclerview.
  *
  * @see #oncreateviewholder(viewgroup, int)
  */
 public final vh createviewholder(viewgroup parent, int viewtype) {
   tracecompat.beginsection(trace_create_view_tag);
   final vh holder = oncreateviewholder(parent, viewtype);
   holder.mitemviewtype = viewtype;
   tracecompat.endsection();
   return holder;
 }

 /**
  * this method internally calls {@link #onbindviewholder(viewholder, int)} to update the
  * {@link viewholder} contents with the item at the given position and also sets up some
  * private fields to be used by recyclerview.
  *
  * @see #onbindviewholder(viewholder, int)
  */
 public final void bindviewholder(vh holder, int position) {
   holder.mposition = position;
   if (hasstableids()) {
     holder.mitemid = getitemid(position);
   }
   holder.setflags(viewholder.flag_bound,
       viewholder.flag_bound | viewholder.flag_update | viewholder.flag_invalid
           | viewholder.flag_adapter_position_unknown);
   tracecompat.beginsection(trace_bind_view_tag);
   onbindviewholder(holder, position, holder.getunmodifiedpayloads());
   holder.clearpayload();
   tracecompat.endsection();
 }

 /**
  * return the view type of the item at <code>position</code> for the purposes
  * of view recycling.
  *
  * <p>the default implementation of this method returns 0, making the assumption of
  * a single view type for the adapter. unlike listview adapters, types need not
  * be contiguous. consider using id resources to uniquely identify item view types.
  *
  * @param position position to query
  * @return integer value identifying the type of the view needed to represent the item at
  *         <code>position</code>. type codes need not be contiguous.
  */
 public int getitemviewtype(int position) {
   return 0;
 }

 /**
  * returns the total number of items in the data set hold by the adapter.
  *
  * @return the total number of items in this adapter.
  */
 public abstract int getitemcount();

 /**
  * called when a view created by this adapter has been attached to a window.
  *
  * <p>this can be used as a reasonable signal that the view is about to be seen
  * by the user. if the adapter previously freed any resources in
  * {@link #onviewdetachedfromwindow(recyclerview.viewholder) onviewdetachedfromwindow}
  * those resources should be restored here.</p>
  *
  * @param holder holder of the view being attached
  */
 public void onviewattachedtowindow(vh holder) {
 }

 /**
  * called when a view created by this adapter has been detached from its window.
  *
  * <p>becoming detached from the window is not necessarily a permanent condition;
  * the consumer of an adapter's views may choose to cache views offscreen while they
  * are not visible, attaching an detaching them as appropriate.</p>
  *
  * @param holder holder of the view being detached
  */
 public void onviewdetachedfromwindow(vh holder) {
 }

 /**
  * register a new observer to listen for data changes.
  *
  * <p>the adapter may publish a variety of events describing specific changes.
  * not all adapters may support all change types and some may fall back to a generic
  * {@link android.support.v7.widget.recyclerview.adapterdataobserver#onchanged()
  * "something changed"} event if more specific data is not available.</p>
  *
  * <p>components registering observers with an adapter are responsible for
  * {@link #unregisteradapterdataobserver(recyclerview.adapterdataobserver)
  * unregistering} those observers when finished.</p>
  *
  * @param observer observer to register
  *
  * @see #unregisteradapterdataobserver(recyclerview.adapterdataobserver)
  */
 public void registeradapterdataobserver(adapterdataobserver observer) {
   mobservable.registerobserver(observer);
 }

 /**
  * unregister an observer currently listening for data changes.
  *
  * <p>the unregistered observer will no longer receive events about changes
  * to the adapter.</p>
  *
  * @param observer observer to unregister
  *
  * @see #registeradapterdataobserver(recyclerview.adapterdataobserver)
  */
 public void unregisteradapterdataobserver(adapterdataobserver observer) {
   mobservable.unregisterobserver(observer);
 }

 /**
  * called by recyclerview when it starts observing this adapter.
  * <p>
  * keep in mind that same adapter may be observed by multiple recyclerviews.
  *
  * @param recyclerview the recyclerview instance which started observing this adapter.
  * @see #ondetachedfromrecyclerview(recyclerview)
  */
 public void onattachedtorecyclerview(recyclerview recyclerview) {
 }

 /**
  * called by recyclerview when it stops observing this adapter.
  *
  * @param recyclerview the recyclerview instance which stopped observing this adapter.
  * @see #onattachedtorecyclerview(recyclerview)
  */
 public void ondetachedfromrecyclerview(recyclerview recyclerview) {
 }

 /**
  * notify any registered observers that the data set has changed.
  */
 public final void notifydatasetchanged() {
   mobservable.notifychanged();
 }

 /**
  * notify any registered observers that the item at <code>position</code> has changed.
  * equivalent to calling <code>notifyitemchanged(position, null);</code>.
  *
  * <p>this is an item change event, not a structural change event. it indicates that any
  * reflection of the data at <code>position</code> is out of date and should be updated.
  * the item at <code>position</code> retains the same identity.</p>
  *
  * @param position position of the item that has changed
  *
  * @see #notifyitemrangechanged(int, int)
  */
 public final void notifyitemchanged(int position) {
   mobservable.notifyitemrangechanged(position, 1);
 }

 /**
  * notify any registered observers that the item reflected at <code>fromposition</code>
  * has been moved to <code>toposition</code>.
  *
  * <p>this is a structural change event. representations of other existing items in the
  * data set are still considered up to date and will not be rebound, though their
  * positions may be altered.</p>
  *
  * @param fromposition previous position of the item.
  * @param toposition new position of the item.
  */
 public final void notifyitemmoved(int fromposition, int toposition) {
   mobservable.notifyitemmoved(fromposition, toposition);
 }
}

adapter是recyclerview的一个抽象内部类,我们只需要重写它暴露出来的各种回调方法(创建view,绑定view,获取数据内容,通知数据变化......),就可以达到创建及控制itemview内容的目的。这里挑我们创建adapter时常用的重写方法讲解:

oncreateviewholder:

根据需求,创建自定义样式的itemviw,最终return一个viewholder类型。由adapter内部类中的createviewholder调用。

//根据需求,创建自定义样式的itemviw
 @override
 public viewholder oncreateviewholder(viewgroup viewgroup, int viewtype) {
   view view = layoutinflater.from(viewgroup.getcontext()).inflate(r.layout.item,viewgroup,false);
   viewholder vh = new viewholder(view);
   return vh;
 }

onbindviewholder:

将我们传递进来的数据bean与view绑定在一起,即决定我们的itemview的具体内容如何展示,由adapter内部类中的bindviewholder调用。同时也可以在这里处理触摸事件的回调,后面会讲到。

 //将数据与界面进行绑定的操作
 @override
 public void onbindviewholder(viewholder viewholder, int position) {
   viewholder.mtextview.settext(datas[position]);
 }

getitemcount:

返回数据bean的数量,即需要的itemview的个数。

//获取数据的数量
 @override
 public int getitemcount() {
   return datas.length;
 }

一般情况我们重写上述三个方法即可。

onviewattachedtowindow onviewdetachedfromwindow:

在view依附/脱离window的时候回调

registeradapterdataobserver unregisteradapterdataobserver:

主要用于注册与解绑适配器数据的观察者模式

notifydatasetchanged notifyitemmoved:

通过adapter来通知数据或item的变化,请求更新view.

那怎么让adapter来为我们处理触摸事件?通过接口回调的方法就能很简单地完成。
首先在我们的adapter中添加一个内部接口,其中的方法在第一步实例化view的时候实现。

 public interface onitemclicklistener {
    void itemclicklistener(view view,int postion);
    void itemlongclicklistener(view view,int postion);

  }

然后在onbindviewholder中回调。

  if(mlistener!=null){//如果设置了监听那么它就不为空,然后回调相应的方法
      holder.itemview.setonclicklistener(new view.onclicklistener() {
        @override
        public void onclick(view v) {
          int pos = holder.getlayoutposition();//得到当前点击item的位置pos
          mlistener.itemclicklistener(holder.itemview,pos);//把事件交给我们实现的接口那里处理
        }
      });
      holder.itemview.setonlongclicklistener(new view.onlongclicklistener() {
        @override
        public boolean onlongclick(view v) {
          int pos = holder.getlayoutposition();//得到当前点击item的位置pos
          mlistener.itemlongclicklistener(holder.itemview,pos);//把事件交给我们实现的接口那里处理
          return true;
        }
      });
    }

3.将recyclerview与adapter通过setadapter联系起来,并实现adapter内部的回调接口。

  adapter=new myrecycleradapter(this, list);
   mrecycler.setadapter(adapter);
   adapter.setonclicklistener(new myrecycleradapter.onitemclicklistener() {
     @override
     public void itemclicklistener(view view, int postion) {
       toast.maketext(mainactivity.this,"点击了:"+postion, toast.length_short).show();
     }

     @override
     public void itemlongclicklistener(view view, int postion) {
       list.remove(postion);
       adapter.notifyitemremoved(postion);
     }
   });

至此一个最简单的recyclerviewadapter就完成了,文末给出一个自己简单封装过后的commonrecycleradapter,使用时我们只需要传入 context, layoutresid,list<t> data即可。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!