Tangram系列(三) android Tangram源码分析

知识回顾

前面的文章分析了Tangram的结构,以及组织数据和模块的方式。Tangram中一个列表页面分成了多个card卡片,每个card卡片内部的结构:head+多个cell组件+foot。Tangram对页面的这种管理可以满足不同的card,布局样式不同,比如card有gridview样式,一拖N样式,轮播图等等,达到了一个RecyclerView内部不同的区域样式不同,相对系统一个RecyclerView只能一种样式的方案,布局更灵活。本篇文章将分析Tangram如何实现将下发的json数据显示页面的源码实现。

Tangram实现了什么

Tangram实现动态化构建native页面的框架。根据后台配置的json数据,实现json数据的解析,解析的数据包含布局信息和业务数据信息。RecyclerView根据json解析的数据模型中的布局信息,创建native view,以及利用数据模型的业务数据信息绑定view。而RecyclerView 的item可以实现多样化的布局,它依赖的V-Layout实现,V-Layout满足了RecyclerView的item布局的多样性。Tangram更像是一个解耦框架,自定义不同的数据模型和view视图。Tangram2.0还支持了新的功能VirtualView。

tangram内部框架结构

tangram-cls.png

主要类说明:

  1. Tangram.Builder: 构建数据模型和组件模型。主要是产生两个映射表,数据模型的type-->数据模型的class,组件的type-->组件的class。json数据的解析以及组件的构建依赖这两个映射表。
  2. TangramEngine:组织数据解析器解析数据模型,根据数据模型构建布局管理器VirtualLayoutManager,和数据适配器PojoGroupAdapter,以及将Recyclerview初始化,绑定适配器和布局管理器。
  3. DataParser:数据解析器,根据json对象的type字段,实例化数据模型,依据mCardResolver和mcellResolver内部的映射表,利用反射实例化数据模型。
  4. VirtualLayoutManager:是RecyclerView的布局管理器,它根据itemView的布局类型,找到与itemView对应的布局工具layoutHelper,由LayoutHelper完成布局计算。VirtualLayoutManager和LayoutHelper是V-Layout内部的类。
  5. PojoGroupBasicAdapter是RecyclerView的适配器。

Tangram的工作流程

Tangram流程图 (1).png
  1. 初始化组件库,卡片库,以及数据模型。Tangram采用的是集中式的管理组件,卡片以及数据模型。这种管理方式优点是管理集中,缺点是扩展时需要修改初始化代码,容易出错。可以用分布式的方式替换,如注解的方式,扩展更便捷,不需要修改初始化逻辑。
  2. 构建引擎。
  3. 绑定RecyclerView。
  4. 解析json数据,转换为卡片+组件的model,并绑定到布局框架,完成卡片渲染。

Tangram源码分析

初始化组件+卡片model,view+布局库

  • 卡片model注册到CardResolver,注册的是type与card class的映射
  • 组件model注册到MVResolver,注册的是type与cell class的映射。
  • 布局注册到BaseCardBinderResolver,注册的是type与BaeLayoutBinder 实例对象的映射。
  • view注册到BaseCellBinderResolver,注册的是type与BaseCellBinder实例对象的映射,BaseCelBinder内部创建view实例。
  • 为什么view解析过程封装了多层?为了支持动态view--VirtualView
public static void installDefaultRegistry(@NonNull final DefaultResolverRegistry registry)
{
            /*
             * register built-in cards & mCells
             */
        MVHelper mvHelper = new MVHelper(new MVResolver());
        registry.setMVHelper(mvHelper);

        // built-in mCells
        registry.registerCell(TYPE_EXTENDED_VIEW_COMPACT, Card.PlaceholderCell.class,
            SimpleEmptyView.class);
        registry.registerCell(TYPE_EMPTY_VIEW_COMPACT, BaseCell.class, SimpleEmptyView.class);
        //registry.registerCell(TYPE_SIMPLE_IMAGE_COMPACT, Cell.class, SimpleImgView.class);
        registry.registerCell(TYPE_CAROUSEL_CELL_COMPACT, BannerView.class);
        registry.registerCell(TYPE_CONTAINER_BANNER, BannerView.class);
        registry.registerCell(TYPE_LINEAR_SCROLL_CELL_COMPACT, LinearScrollView.class);
        registry.registerCell(TYPE_CONTAINER_SCROLL, LinearScrollView.class);

        // built-in cards
        registry.registerCard(TYPE_CAROUSEL_COMPACT, BannerCard.class);
        registry.registerCard(TYPE_CONTAINER_BANNER, BannerCard.class);
        registry.registerCard(TYPE_SINGLE_COLUMN_COMPACT, SingleColumnCard.class);
        ...
        // extend cards
        registry.registerCard(TYPE_FIX_COMPACT, FixCard.class);
        registry.registerCard(TYPE_GRID_COMPACT, GridCard.class);
        registry.registerCard(TYPE_LINEAR_COMPACT, LinearCard.class);
        registry.registerCard(TYPE_X_COLUMN_COMPACT, ColumnCard.class);
    }

绑定RecyclerView


    public void bindView(@NonNull final RecyclerView view) {
        //noinspection ConstantConditions
        Preconditions.checkArgument(view != null, "view must not be null");
        if (mContentView != null) {
            mContentView.setAdapter(null);
            mContentView.setLayoutManager(null);
        }

        this.mContentView = view;
        this.mContentView.setLayoutManager(mLayoutManager);
        mLayoutManager.setPerformanceMonitor(mPerformanceMonitor);
        if (mGroupBasicAdapter == null) {
            this.mGroupBasicAdapter = mAdapterBuilder.newAdapter(mContext, mLayoutManager, this);
            mGroupBasicAdapter.setPerformanceMonitor(mPerformanceMonitor);
            mGroupBasicAdapter.setErrorSupport(getService(InternalErrorSupport.class));
        }

        if (mContentView.getRecycledViewPool() != null) {
            mContentView.setRecycledViewPool(new InnerRecycledViewPool(mContentView.getRecycledViewPool()));
        }
  • 给RecyclerView配置adapter
  • 配置布局管理器
  • 配置回收池,回收池会在全局范围共享,组件以及Recyclerview共享这个回收池。

解析json数据,构建card+cell 模型

//PojoDataParser.java
    @Override
    public List<Card> parseGroup(@NonNull JSONArray data, @NonNull final ServiceManager serviceManager) {
        final CardResolver cardResolver = serviceManager.getService(CardResolver.class);
        Preconditions.checkState(cardResolver != null, "Must register CardResolver into ServiceManager first");
        final MVHelper cellResolver = serviceManager.getService(MVHelper.class);
        Preconditions.checkState(cellResolver != null, "Must register CellResolver into ServiceManager first");
        final int size = data.length();
        final List<Card> result = new ArrayList<>(size);
        for (int i = 0; i < size; i++) {
            JSONObject cardData = data.optJSONObject(i);
            final Card card = parseSingleGroup(cardData, serviceManager);
            if (card != null) {
                if (card instanceof IDelegateCard) {
                    List<Card> cards = ((IDelegateCard) card).getCards(new CardResolver() {
                        @Override
                        public Card create(String type) {
                            Card c = cardResolver.create(type);
                            c.serviceManager = serviceManager;
                            c.id = card.id;
                            c.setStringType(type);
                            c.rowId = card.rowId;
                            return c;
                        }
                    });
                    for (Card c : cards) {
                        if (c.isValid()) {
                            result.add(c);
                        }
                    }
                } else {
                    result.add(card);
                }
            }
        }
        cellResolver.resolver().setCards(result);
        return result;
    }
  • 根据CardResolver构建card实例
  • 在card类内部解析cell
  • 根据MvResolver构建cell实例

为adapter设置数据并构建layoutHelper

// GroupBasicAdapter.java
public void setData(@Nullable List<L> cards, boolean silence) {
        createSnapshot();

        mCards.clear();
        mData.clear();


        if (cards != null && cards.size() != 0) {
            mCards.ensureCapacity(cards.size());
            setLayoutHelpers(transformCards(cards, mData, mCards));
        } else {
            setLayoutHelpers(Collections.<LayoutHelper>emptyList());
        }

        diffWithSnapshot();

        if (!silence)
            notifyDataSetChanged();
    }
     @NonNull
    protected List<LayoutHelper> transformCards(@Nullable List<L> cards, final @NonNull List<C> data,
                                                @NonNull List<Pair<Range<Integer>, L>> rangeCards) {
        if (cards == null || cards.size() == 0) {
            return new LinkedList<>();
        }


        int lastPos = data.size();
        List<LayoutHelper> helpers = new ArrayList<>(cards.size());
        for (int i = 0, size = cards.size(); i < size; i++) {
            L card = cards.get(i);

            if (card == null) continue;

            final String ctype = getCardStringType(card);
            List<C> items = getItems(card);
            if (items == null) {
                // skip card null
                continue;
            }

            data.addAll(items);

            // calculate offset to set ranges
            int offset = lastPos;
            lastPos += items.size();
            // include [x, x) for empty range, upper are not included in range
            rangeCards.add(Pair.create(Range.create(offset, lastPos), card));

            // get layoutHelper for this card
            LayoutBinder<L> binder = mCardBinderResolver.create(ctype);
            LayoutHelper helper = binder.getHelper(ctype, card);


            if (helper != null) {
                helper.setItemCount(items.size());
                helpers.add(helper);
            }
        }

        return helpers;
    }
    //BaseCardBinderResolver.java
      public BaseLayoutBinder create(String type) {
        if (mDelegate.hasType(type)) {
            return new BaseLayoutBinder();
        }
        return null;
    }
// BaseLayoutBinder.java
   public LayoutHelper getHelper(String type, Card data) {
        if (data == null) return null;
        return data.getLayoutHelper();
    }
    //
  • layoutHelper的构建过程:根据BaseCardBinderResolver的create方法,构建BaseLayoutBinder,然后在BaseLayoutBinder的getHelper中调用形参card.getLayoutHelper获得LayoutHelper,card与layoutHelper是一 一对应的,不同type的card对应的LayoutHelper不同。

Recyclerview渲染过程构建view

//GroupBasicAdapter.java
  @Override
    public BinderViewHolder<C, ? extends View> onCreateViewHolder(ViewGroup parent, int viewType) {
        String cellType = getCellTypeFromItemType(viewType);
        ControlBinder<C, ? extends View> binder = mCompBinderResolver.create(cellType);
        if (mPerformanceMonitor != null) {
            mPerformanceMonitor.recordStart(PHASE_CREATE, cellType);
        }

        if (null == binder && null != errorSupport) {
            Map<String, Object> infoMap = new HashMap<>();
            infoMap.put("type", cellType);
            infoMap.put("binderResolver", mCompBinderResolver.toString());
            errorSupport.onError(InternalErrorSupport.ERROR_CREATE_VIEWHOLDER_NOT_FOUND_TYPE,
                    "Couldn't found component match certain type: " + cellType, infoMap);
        }

        BinderViewHolder binderViewHolder = createViewHolder(binder, mContext, parent);
        if (mPerformanceMonitor != null) {
            mPerformanceMonitor.recordEnd(PHASE_CREATE, cellType);
        }
        return binderViewHolder;
    }
    //PojoGroupBasicAdapter.java
      @Override
    public <V extends View> BinderViewHolder<BaseCell, V> createViewHolder(@NonNull ControlBinder<BaseCell, V> binder, @NonNull Context context, ViewGroup parent) {
        V view = binder.createView(context, parent);
        return new BinderViewHolder<>(view, binder);
    }
    //BaseCellBinder.java
    public V createView(Context context, ViewGroup parent) {
        V v;
        if (viewHolderCreator != null) {
            v = viewHolderCreator.create(context, parent);
        } else if (mViewCreator != null) {
            v = mViewCreator.create(context, parent);
        } else {
            v = (V) mMvHelper.getVafContext().getContainerService().getContainer(type, true);
        }crea
        if (v.getId() <= 0) {
            v.setId(R.id.TANGRAM_VIEW_CONTAINER_ID);
        }

        return v;
    }
    //ViewCreator.java
    public V create(@NonNull Context context, ViewGroup parent) {
        try {
            Constructor<V> constructor = mClz.getConstructor(Context.class);
            view = constructor.newInstance(context);
            return view;
        } catch (InstantiationException e) {
            handleException(e);
        } catch (IllegalAccessException e) {
            handleException(e);
        } catch (InvocationTargetException e) {
            handleException(e);
        } catch (NoSuchMethodException e) {
            handleException(e);
        }

        throw new RuntimeException("Failed to create View of class: " + mClz.getName());
    }
  • view的构建过程:在BaseCellBinderResolver根据view的type,从其mSparseArray属性中获取BaseCellBinder实例调用BaseCellBinder.createView方法,createView方法内部调用ViewCreator类的create方法,返回view实例。或者createView在ViewHolderCreator或者MVHelper中获得view实例。

几点疑惑

  1. layoutHelper是BaseLBaseL'LayoutBinder创建的,为什么包装了一层BaseCardBinderResolver?

在注册的时候发现,BaseCardBinderResolver并没有对type和BaselayoutBinder映射,BaseCardBinderResolver构建的时候传入一个代理CardResolver,这个代理在这里完成了两件事情: - 容错type类型,cardResolver不支持的类型,BaseCrdBinderResolver 不处理,丢弃掉。- 获取支持的类型个数。
由此可见BaseCardBinderResolver主要起到过滤type的作用,而BaseLayoutBinder主要构建layoutHelper,这样每个类的功能划分明确。

2.BaseCellBinderResolver与BaseCellBinder功能能否合并为一个类?

BaseCellBinderResolver中注册type与BaseCellBinder的映射表,为了后面查询使用,而BaseCellBinder的作用是构建view实例,有三中方式:viewCreator,viewHolderCreater以及mvHelper。可见二者的功能划分是很明确的,不能合并。

推荐阅读更多精彩内容