美文网首页
装饰设计模式在Android开发中的应用

装饰设计模式在Android开发中的应用

作者: 老师好我是小明同学 | 来源:发表于2020-01-14 20:25 被阅读0次
    1. 模式定义

    装饰设计模式也称包装设计模式,用来动态的扩展对象的功能,也是继承关系的的一种替代方案之一。在不使用的继承的方式下,采用装饰设计模式可以扩展一个对象的功能,可以使一个对象变得越来越强大。

    2. Android 源码的学习和思考

    相信用过 ListView 的朋友都知道,ListView 有自带的方法可以添加 header 和 footer,那么 ListView 是怎样做到的呢?

    ListView.java 的源码

    ArrayList<FixedViewInfo> mHeaderViewInfos = Lists.newArrayList();
    ArrayList<FixedViewInfo> mFooterViewInfos = Lists.newArrayList();
    
    public void addHeaderView(View v, Object data, boolean isSelectable) {
            if (v.getParent() != null && v.getParent() != this) {
                if (Log.isLoggable(TAG, Log.WARN)) {
                    Log.w(TAG, "The specified child already has a parent. "
                               + "You must call removeView() on the child's parent first.");
                }
            }
            final FixedViewInfo info = new FixedViewInfo();
            info.view = v;
            info.data = data;
            info.isSelectable = isSelectable;
            mHeaderViewInfos.add(info);
            mAreAllItemsSelectable &= isSelectable;
    
            // Wrap the adapter if it wasn't already wrapped.
            if (mAdapter != null) {
                if (!(mAdapter instanceof HeaderViewListAdapter)) {
                    wrapHeaderListAdapterInternal();
                }
    
                // In the case of re-adding a header view, or adding one later on,
                // we need to notify the observer.
                if (mDataSetObserver != null) {
                    mDataSetObserver.onChanged();
                }
            }
        }
        
    protected void wrapHeaderListAdapterInternal() {
            mAdapter = wrapHeaderListAdapterInternal(mHeaderViewInfos, mFooterViewInfos, mAdapter);
        }
        
    protected HeaderViewListAdapter wrapHeaderListAdapterInternal(
                ArrayList<ListView.FixedViewInfo> headerViewInfos,
                ArrayList<ListView.FixedViewInfo> footerViewInfos,
                ListAdapter adapter) {
            return new HeaderViewListAdapter(headerViewInfos, footerViewInfos, adapter);
        }
    

    类关系

    public interface WrapperListAdapter extends ListAdapter {
        /**
         * Returns the adapter wrapped by this list adapter.
         *
         * @return The {@link android.widget.ListAdapter} wrapped by this adapter.
         */
        public ListAdapter getWrappedAdapter();
    }
    
    -----------------------------------------------
    
    public class HeaderViewListAdapter implements WrapperListAdapter, Filterable {
        ...
    }
    

    可以看到 adapter 是 HeaderViewListAdapter 的子类的时候,会最终将 headerView 和 footerView 配置到 HeaderViewListAdapter 中实现。那么 HeaderViewListAdapter 是怎样实现的呢?

    HeaderViewListAdapter.java 主要源码

    public class HeaderViewListAdapter implements WrapperListAdapter, Filterable {
    
        private final ListAdapter mAdapter;
    
        ArrayList<ListView.FixedViewInfo> mHeaderViewInfos;
        ArrayList<ListView.FixedViewInfo> mFooterViewInfos;
    
        static final ArrayList<ListView.FixedViewInfo> EMPTY_INFO_LIST =
            new ArrayList<ListView.FixedViewInfo>();
            
        public HeaderViewListAdapter(ArrayList<ListView.FixedViewInfo> headerViewInfos,
                                     ArrayList<ListView.FixedViewInfo> footerViewInfos,
                                     ListAdapter adapter) {
            mAdapter = adapter;
            ...
            if (headerViewInfos == null) {
                mHeaderViewInfos = EMPTY_INFO_LIST;
            } else {
                mHeaderViewInfos = headerViewInfos;
            }
    
            if (footerViewInfos == null) {
                mFooterViewInfos = EMPTY_INFO_LIST;
            } else {
                mFooterViewInfos = footerViewInfos;
            }
            ...
        }
        
        public boolean removeHeader(View v) {
            for (int i = 0; i < mHeaderViewInfos.size(); i++) {
                ListView.FixedViewInfo info = mHeaderViewInfos.get(i);
                if (info.view == v) {
                    mHeaderViewInfos.remove(i);
    
                    mAreAllFixedViewsSelectable =
                            areAllListInfosSelectable(mHeaderViewInfos)
                            && areAllListInfosSelectable(mFooterViewInfos);
    
                    return true;
                }
            }
    
            return false;
        }
    
        public boolean removeFooter(View v) {
            for (int i = 0; i < mFooterViewInfos.size(); i++) {
                ListView.FixedViewInfo info = mFooterViewInfos.get(i);
                if (info.view == v) {
                    mFooterViewInfos.remove(i);
    
                    mAreAllFixedViewsSelectable =
                            areAllListInfosSelectable(mHeaderViewInfos)
                            && areAllListInfosSelectable(mFooterViewInfos);
    
                    return true;
                }
            }
    
            return false;
        }
        
        public int getCount() {
            if (mAdapter != null) {
                return getFootersCount() + getHeadersCount() + mAdapter.getCount();
            } else {
                return getFootersCount() + getHeadersCount();
            }
        }
        
        public Object getItem(int position) {
            // Header (negative positions will throw an IndexOutOfBoundsException)
            int numHeaders = getHeadersCount();
            if (position < numHeaders) {
                return mHeaderViewInfos.get(position).data;
            }
    
            // Adapter
            final int adjPosition = position - numHeaders;
            int adapterCount = 0;
            if (mAdapter != null) {
                adapterCount = mAdapter.getCount();
                if (adjPosition < adapterCount) {
                    return mAdapter.getItem(adjPosition);
                }
            }
    
            // Footer (off-limits positions will throw an IndexOutOfBoundsException)
            return mFooterViewInfos.get(adjPosition - adapterCount).data;
        }
        
        public View getView(int position, View convertView, ViewGroup parent) {
            // Header (negative positions will throw an IndexOutOfBoundsException)
            int numHeaders = getHeadersCount();
            if (position < numHeaders) {
                return mHeaderViewInfos.get(position).view;
            }
    
            // Adapter
            final int adjPosition = position - numHeaders;
            int adapterCount = 0;
            if (mAdapter != null) {
                adapterCount = mAdapter.getCount();
                if (adjPosition < adapterCount) {
                    return mAdapter.getView(adjPosition, convertView, parent);
                }
            }
    
            // Footer (off-limits positions will throw an IndexOutOfBoundsException)
            return mFooterViewInfos.get(adjPosition - adapterCount).view;
        }
    
    }
    

    可以看到,HeaderViewListAdapter 在 ListAdapter 的基础上,且不修改 原有开发者自行定义的 Adapter下,对 ListView 提供了支持 header 和 footer 的添加。所以, ListView 的源码是通过装饰设计模式让其具有添加 header 和 footer 的能力。

    RecycleView 没有相关的方法,应该怎样才可以 添加 header 和 footer?这时,通过学习 ListView 的源码后,不就可以使用装饰设计模式轻松解决问题了吗?!

    2. 使用装饰设计模式让 RecycleView 也可添加 header 和 footer

    好,那么我们从装饰 Adapter 入手,鉴于本文是介绍如何使用装饰设计模式解决问题,此处实例仅供参考学习,如实际应用有问题,应自行完善和拓展

    自己动手写一个 HeaderViewListAdapter.java

    public class HeaderViewListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
        // 装饰 RecyclerView.Adapter
        private final RecyclerView.Adapter mRealAdapter;
        ArrayList<View> mHeaderViews;
        ArrayList<View> mFooterViews;
    
        public HeaderViewListAdapter(RecyclerView.Adapter realAdapter){
            this.mRealAdapter = realAdapter;
    
            mRealAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
                @Override
                public void onChanged() {
                    notifyDataSetChanged();
                }
            });
    
            mHeaderViews = new ArrayList<>();
            mFooterViews = new ArrayList<>();
        }
    
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int position) {
            // 头部返回 头部的ViewHolder
            int numHeaders = getHeadersCount();
            if (position < numHeaders) {
                return createHeaderFooterViewHolder(mHeaderViews.get(position));
            }
            // mRealAdapter 返回 mRealAdapter的ViewHolder
            final int adjPosition = position - numHeaders;
            int adapterCount = 0;
            if (mRealAdapter != null) {
                adapterCount = mRealAdapter.getItemCount();
                if (adjPosition < adapterCount) {
                    // 直接传 position ,不兼容 万能适配多布局条目
                    return mRealAdapter.onCreateViewHolder(parent,mRealAdapter.getItemViewType(adjPosition));
                }
            }
            // 底部返回 底部的ViewHolder
            // Footer (off-limits positions will throw an IndexOutOfBoundsException)
            return createHeaderFooterViewHolder(mFooterViews.get(adjPosition - adapterCount));
        }
    
        private RecyclerView.ViewHolder createHeaderFooterViewHolder(View view) {
            return new RecyclerView.ViewHolder(view){};
        }
    
        public int getHeadersCount() {
            return mHeaderViews.size();
        }
    
        public int getFootersCount() {
            return mFooterViews.size();
        }
    
        @Override
        public int getItemViewType(int position) {
            // 把位置作为 viewType
            return position;
        }
    
        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            // 这个方法先不写,测试一下
            // 头部和底部是都不需要做处理的,只要 mRealAdapter 要去做处理
            int numHeaders = getHeadersCount();
            if (position < numHeaders) {
                return ;
            }
    
            final int adjPosition = position - numHeaders;
            int adapterCount = 0;
            if (mRealAdapter != null) {
                adapterCount = mRealAdapter.getItemCount();
                if (adjPosition < adapterCount) {
                    mRealAdapter.onBindViewHolder(holder,position);
                }
            }
        }
    
        @Override
        public int getItemCount() { // 总共返回多少条 = 底部条数+头部条数+真实的Adapter条数
            return mFooterViews.size()+mHeaderViews.size()+mRealAdapter.getItemCount();
        }
    
        /**
         * 添加头部
         * @param view
         */
        public void addHeaderView(View view){
            if(!mHeaderViews.contains(view)){
                mHeaderViews.add(view);
                notifyDataSetChanged();
            }
        }
    
        /**
         * 添加底部
         * @param view
         */
        public void addFooterView(View view){
            if(!mFooterViews.contains(view)){
                mFooterViews.add(view);
                notifyDataSetChanged();
            }
        }
    
        /**
         * 移除头部
         * @param view
         */
        public void removeHeaderView(View view){
            if(mHeaderViews.contains(view)){
                mHeaderViews.remove(view);
                notifyDataSetChanged();
            }
        }
    
        /**
         * 移除底部
         * @param view
         */
        public void removeFooterView(View view){
            if(mFooterViews.contains(view)){
                mFooterViews.remove(view);
                notifyDataSetChanged();
            }
        }
    }
    
    

    ListView 中直接提供了方法添加 header 和 footer,那我们需要自定义拓展 RecyclerView 来添加相关的方法

    HeaderViewRecyclerView.java

    public class HeaderViewRecyclerView extends RecyclerView{
    
        private HeaderViewListAdapter mAdapter;
    
        public HeaderViewRecyclerView(Context context) {
            super(context);
        }
    
        public HeaderViewRecyclerView(Context context, @Nullable AttributeSet attrs) {
            super(context, attrs);
        }
    
        public HeaderViewRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
        }
    
        @Override
        public void setAdapter(Adapter adapter) {
            mAdapter = new HeaderViewListAdapter(adapter);
            super.setAdapter(mAdapter);
        }
    
        /**
         * 添加头部
         * @param view
         */
        public void addHeaderView(View view){
            // 必须要设置 Adapter 之后才能添加头部和底部
            if(mAdapter != null){
                mAdapter.addHeaderView(view);
            }
        }
    
        /**
         * 添加底部
         * @param view
         */
        public void addFooterView(View view){
            if(mAdapter != null){
                mAdapter.addFooterView(view);
            }
        }
    
        /**
         * 移除头部
         * @param view
         */
        public void removeHeaderView(View view){
            if(mAdapter != null){
                mAdapter.removeHeaderView(view);
            }
        }
    
        /**
         * 移除底部
         * @param view
         */
        public void removeFooterView(View view){
            if(mAdapter != null){
                mAdapter.removeFooterView(view);
            }
        }
    }
    
    3. 使用示例
            mRecyclerView.setAdapter(new RecyclerAdapter());
            View headerView = LayoutInflater.from(this).inflate(R.layout.layout_header_view,mRecyclerView,false);
            mRecyclerView.addHeaderView(headerView);
            View footerView = LayoutInflater.from(this).inflate(R.layout.layout_header_view,mRecyclerView,false);
            mRecyclerView.addFooterView(headerView);
    

    其实,就是正常操作使用 RecyclerView,addHeaderView 和 addFooterView 需在 setAdapter 后。

    希望读者能从中感受到到 装饰设计模式 的魅力。

    相关文章

      网友评论

          本文标题:装饰设计模式在Android开发中的应用

          本文链接:https://www.haomeiwen.com/subject/pzoaactx.html