美文网首页程序员
从View的源码分析RN自定义控件显示异常问题

从View的源码分析RN自定义控件显示异常问题

作者: 牟乘风 | 来源:发表于2018-05-30 10:41 被阅读4次

    最近为RN做了一个轮播图的控件,在native代码中运行的很好,但是放入RN之后只能显示最开始的两张图,后面就是空白了,用LayoutInspect一看,view的大小居然是0,通过日志发现原来是没有调measure方法和layout方法。

    导致该现象的罪魁祸首是ReactRootView。该控件作为RN的最终容器,却空实现了onLayout方法以及onMeasure没有测量children 1.png 经过多方请教,可以通过复写requestLayout()解决该问题: 2.png

    如果你熟悉了View的工作机制,那你应该能理解这个解决方案,如果不理解,可以向下看
    为了解释这个问题,我们需要先看requestLayout()的前因后果

    1. 完整代码

    可以先跳过看完整代码,先放上完整代码是为了方便后面的解释

    public class PafTurnPlayer extends FrameLayout implements ViewPager.OnPageChangeListener {
    
        private Runnable mLayoutRunnable;
        private ViewPager mViewPager;
        private String[] mUrls;
        private List<SimpleDraweeView> unusedList = new ArrayList<>();
        private int delay = 2000; // 默认轮播时间
    
        final Runnable runnable = new Runnable() {
            @Override
            public void run() {
                if (getContext() != null) {
                    int currentItem = mViewPager.getCurrentItem();
                    mViewPager.setCurrentItem(currentItem + 1, true);
                }
            }
        };
    
        public PafTurnPlayer(@NonNull Context context) {
            super(context);
            init(context);
        }
    
        public PafTurnPlayer(@NonNull Context context, @Nullable AttributeSet attrs) {
            super(context, attrs);
            init(context);
        }
    
        public PafTurnPlayer(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
            init(context);
        }
    
        private void init(Context context) {
            mViewPager = new ViewPager(context);
            mViewPager.setAdapter(new TurnPlayerAdapter());
            mViewPager.addOnPageChangeListener(this);
            addView(mViewPager);
        }
    
        void addOnPageChangeListener(ViewPager.OnPageChangeListener listener) {
            mViewPager.addOnPageChangeListener(listener);
        }
    
        void setDelay(int delay) {
            this.delay = delay;
        }
    
        public void setData(String... urls) {
            mUrls = urls;
            mViewPager.getAdapter().notifyDataSetChanged();
            postDelayed(runnable, delay);//开始播放
        }
    
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }
    
        @Override
        public void onPageSelected(int position) {
        }
    
        @Override
        public void onPageScrollStateChanged(int state) {
            if (state == ViewPager.SCROLL_STATE_IDLE) {
                postDelayed(runnable, delay);//恢复自动播放
            } else {
                removeCallbacks(runnable);//禁止自动播放
            }
        }
    
        @Override
        protected void onAttachedToWindow() {
            super.onAttachedToWindow();
    //        postDelayed(runnable, delay);
        }
    
        @Override
        protected void onDetachedFromWindow() {
            super.onDetachedFromWindow();
            removeCallbacks(runnable);
        }
    
        private class TurnPlayerAdapter extends PagerAdapter {
    
            @Override
            public int getCount() {
                return mUrls == null ? 0 : (mUrls.length > 1 ? Integer.MAX_VALUE : mUrls.length);
            }
    
            @Override
            public boolean isViewFromObject(View view, Object object) {
                return object == view;
            }
    
            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                final SimpleDraweeView view;
                if (unusedList.isEmpty()) {
                    view = new SimpleDraweeView(container.getContext());
                    view.getHierarchy().setActualImageScaleType(ScalingUtils.ScaleType.CENTER_INSIDE);
                } else {
                    view = unusedList.remove(0);
                }
                view.setController(Fresco.newDraweeControllerBuilder()
                        .setUri(Uri.parse(mUrls[position % mUrls.length]))
                        .setAutoPlayAnimations(true)
                        .build());
                container.addView(view);
                return view;
            }
    
            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                container.removeView((View) object);
                unusedList.add((SimpleDraweeView) object);
            }
        }
    
        @Override
        public void requestLayout() {
            super.requestLayout();
            if (mLayoutRunnable != null) {
                removeCallbacks(mLayoutRunnable);
            }
            mLayoutRunnable = new Runnable() {
                @Override
                public void run() {
                    measure(MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.EXACTLY),
                            MeasureSpec.makeMeasureSpec(getHeight(), MeasureSpec.EXACTLY));
                    layout(getLeft(), getTop(), getRight(), getBottom());
                }
            };
            post(mLayoutRunnable);
        }
    }
    

    2. 谁调用了requestLayout?

    在View和ViewGroup中有多处调用,在我的代码里instantiateItem方法中和destroyItem方法中调用了container.addView(view)和container.removeView(view),该方法是ViewGroup中的方法,源码如下: 3.png 4.png

    可以看到这两个方法都调用了requestLayout()。

    3. requestLayout()做了些啥?

    看源码View.class 5.png 核心要点在于mParent.requestLayout(),mParent可以简单理解为父容器,这样向上溯源可到ViewRootImpl,该类的requestLayout()实现如下: 6.png checkThread()会判断你调用该方法的线程是否是view创建时的线程(这样说即表明未必是UI线程),scheduleTraversals()源码如下: 7.png 关键点在于mChoreographer.postCallback中的mTraversalRunnable,源码如下 8.png 而mChoreographer.postCallback最终是由mHandler.sendMessageAtTime(msg, dueTime)来实现的。再看doTraversal的会调用performTraversals(),该方法长达850行,但我们关心的是调用performMeasure 9.png 和performLayout 10.png performMeasure源码如下: 11.png 这里会按视图树向下传递,最终会到RN的ReactRootView,但ReactRootView却不会向下传递测量动作,导致其子视图没有size。
    performLayout的源码如下:
        private void performLayout(WindowManager.LayoutParams lp, int desiredWindowWidth,
                int desiredWindowHeight) {
            mLayoutRequested = false;
            mScrollMayChange = true;
            mInLayout = true;
    
            final View host = mView;
            if (DEBUG_ORIENTATION || DEBUG_LAYOUT) {
                Log.v(mTag, "Laying out " + host + " to (" +
                        host.getMeasuredWidth() + ", " + host.getMeasuredHeight() + ")");
            }
    
            Trace.traceBegin(Trace.TRACE_TAG_VIEW, "layout");
            try {
                host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
    
                mInLayout = false;
                int numViewsRequestingLayout = mLayoutRequesters.size();
                if (numViewsRequestingLayout > 0) {
                    // requestLayout() was called during layout.
                    // If no layout-request flags are set on the requesting views, there is no problem.
                    // If some requests are still pending, then we need to clear those flags and do
                    // a full request/measure/layout pass to handle this situation.
                    ArrayList<View> validLayoutRequesters = getValidLayoutRequesters(mLayoutRequesters,
                            false);
                    if (validLayoutRequesters != null) {
                        // Set this flag to indicate that any further requests are happening during
                        // the second pass, which may result in posting those requests to the next
                        // frame instead
                        mHandlingLayoutInLayoutRequest = true;
    
                        // Process fresh layout requests, then measure and layout
                        int numValidRequests = validLayoutRequesters.size();
                        for (int i = 0; i < numValidRequests; ++i) {
                            final View view = validLayoutRequesters.get(i);
                            Log.w("View", "requestLayout() improperly called by " + view +
                                    " during layout: running second layout pass");
                            view.requestLayout();
                        }
                        measureHierarchy(host, lp, mView.getContext().getResources(),
                                desiredWindowWidth, desiredWindowHeight);
                        mInLayout = true;
                        host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
    
                        mHandlingLayoutInLayoutRequest = false;
    
                        // Check the valid requests again, this time without checking/clearing the
                        // layout flags, since requests happening during the second pass get noop'd
                        validLayoutRequesters = getValidLayoutRequesters(mLayoutRequesters, true);
                        if (validLayoutRequesters != null) {
                            final ArrayList<View> finalRequesters = validLayoutRequesters;
                            // Post second-pass requests to the next frame
                            getRunQueue().post(new Runnable() {
                                @Override
                                public void run() {
                                    int numValidRequests = finalRequesters.size();
                                    for (int i = 0; i < numValidRequests; ++i) {
                                        final View view = finalRequesters.get(i);
                                        Log.w("View", "requestLayout() improperly called by " + view +
                                                " during second layout pass: posting in next frame");
                                        view.requestLayout();
                                    }
                                }
                            });
                        }
                    }
    
                }
            } finally {
                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
            }
            mInLayout = false;
        }
    

    核心点在host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight()),该方法也会向下传递布局动作,直到ReactRootView。

    综上所述

    轮播图在播放或者滚动时会触发requestLayout,进而对整个视图树进行重新测量和布局,但ReactRootView阻断了测量和布局的传递,导致了轮播图的item无法更新视图。解决方案也就很好理解了,在requestLayout时我们手动调用了轮播图组件的measure和layout方法,从而接上了整个视图树的重新调整动作。

    完结撒花。

    相关文章

      网友评论

        本文标题:从View的源码分析RN自定义控件显示异常问题

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