Android

View.inflate方法和LayoutInflater.fr

2018-12-28  本文已影响0人  ywy_袁滚滚
<!----------View----------->

  public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
        LayoutInflater factory = LayoutInflater.from(context);
        return factory.inflate(resource, root);
    }
<!----------LayoutInflater------------>

 public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
        return inflate(resource, root, root != null);   
    }
   public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
        final Resources res = getContext().getResources();
  
        final XmlResourceParser parser = res.getLayout(resource);
        try {
            return inflate(parser, root, attachToRoot);
        } finally {
            parser.close();
        }
    }
 public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
        synchronized (mConstructorArgs) {
            Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate");

            final Context inflaterContext = mContext;
            final AttributeSet attrs = Xml.asAttributeSet(parser);
            Context lastContext = (Context) mConstructorArgs[0];
            mConstructorArgs[0] = inflaterContext;
            View result = root;

            try {
                // Look for the root node.
                int type;
                while ((type = parser.next()) != XmlPullParser.START_TAG &&
                        type != XmlPullParser.END_DOCUMENT) {
                    // Empty
                }

                if (type != XmlPullParser.START_TAG) {
                    throw new InflateException(parser.getPositionDescription()
                            + ": No start tag found!");
                }

                final String name = parser.getName();
                

                if (TAG_MERGE.equals(name)) {
                    if (root == null || !attachToRoot) {
                        throw new InflateException("<merge /> can be used only with a valid "
                                + "ViewGroup root and attachToRoot=true");
                    }

                    rInflate(parser, root, inflaterContext, attrs, false);
                } else {
                    // Temp is the root view that was found in the xml
                    final View temp = createViewFromTag(root, name, inflaterContext, attrs);

                    ViewGroup.LayoutParams params = null;

                    if (root != null) {
                        if (DEBUG) {
                            System.out.println("Creating params from root: " +
                                    root);
                        }
                        // Create layout params that match root, if supplied
                        params = root.generateLayoutParams(attrs);
                        if (!attachToRoot) {
                            // Set the layout params for temp if we are not
                            // attaching. (If we are, we use addView, below)
                            temp.setLayoutParams(params);
                        }
                    }

                    if (DEBUG) {
                        System.out.println("-----> start inflating children");
                    }

                    // Inflate all children under temp against its context.
                    rInflateChildren(parser, temp, attrs, true);

                    if (DEBUG) {
                        System.out.println("-----> done inflating children");
                    }

                    // We are supposed to attach all the views we found (int temp)
                    // to root. Do that now.
                    if (root != null && attachToRoot) {
                        root.addView(temp, params);
                    }

                    // Decide whether to return the root that was passed in or the
                    // top view found in xml.
                    if (root == null || !attachToRoot) {
                        result = temp;
                    }
                }

            } catch (XmlPullParserException e) {
                final InflateException ie = new InflateException(e.getMessage(), e);
                ie.setStackTrace(EMPTY_STACK_TRACE);
                throw ie;
            } catch (Exception e) {
                final InflateException ie = new InflateException(parser.getPositionDescription()
                        + ": " + e.getMessage(), e);
                ie.setStackTrace(EMPTY_STACK_TRACE);
                throw ie;
            } finally {
                // Don't retain static reference on context.
                mConstructorArgs[0] = lastContext;
                mConstructorArgs[1] = null;

                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
            }

            return result;
        }
    }
 public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
            View result = root;
            
            final String name = parser.getName();

            if (TAG_MERGE.equals(name)) {
                if (root == null || !attachToRoot) {
                    throw new InflateException("<merge /> can be used only with a valid "
                            + "ViewGroup root and attachToRoot=true");
                }

                rInflate(parser, root, inflaterContext, attrs, false);
            } else {
                // 获取xml中的根view
                final View temp = createViewFromTag(root, name, inflaterContext, attrs);

                ViewGroup.LayoutParams params = null;

                if (root != null) {

                    // Create layout params that match root, if supplied
                    params = root.generateLayoutParams(attrs);
                    if (!attachToRoot) {
                        // Set the layout params for temp if we are not
                        // attaching. (If we are, we use addView, below)
                        //如果ViewGroup root不为null并且attachToRoot == false,为xml获取的根view temp设置 ViewGroup.LayoutParams
                        temp.setLayoutParams(params);
                    }
                }


                // 将temp下所有的子view添加到temp中
                rInflateChildren(parser, temp, attrs, true);  

                //如果ViewGroup root不为null并且attachToRoot == true,将temp添加到root中,并设置 ViewGroup.LayoutParams
                if (root != null && attachToRoot) {
                    root.addView(temp, params);
                }

                // 如果传进来的ViewGroup root为null 或者attachToRoot == false,返回xml中的根view temp,其它情况返回传进来的ViewGroup root
                if (root == null || !attachToRoot) {
                    result = temp;
                }
            }

            return result;  
    }
  1. ViewGroup root == null && attachToRoot == false ====> 返回获取xml中的根view temp,同时temp并没有设置了ViewGroup.LayoutParams(此时如果获取LayoutParams可能为空)
  2. ViewGroup root == null && attachToRoot == true ====> 返回获取xml中的根view temp,同时temp并没有设置了ViewGroup.LayoutParams(此时如果获取LayoutParams可能为空)
  3. ViewGroup root != null && attachToRoot == false====>返回获取xml中的根view temp,同时设置了ViewGroup.LayoutParams
  4. ViewGroup root != null && attachToRoot == true====> 返回ViewGroup root,同时为获取到xml中的根view temp设置了ViewGroup.LayoutParams,并添加到ViewGroup root
  1. 一种是 ViewGroup root == null && attachToRoot == false,此时需要注意的是返回的是xml布局的根View,并且并未为该根View设置ViewGroup.LayoutParams,在这种情况需要获取view的LayoutParams进行操作的需要特别注意
  2. 另外一种是ViewGroup root != null && attachToRoot == true,此时返回的是传入的ViewGroup root,同时为获取到xml中的根view temp设置了ViewGroup.LayoutParams,并添加到ViewGroup root,这种情况需要注意的是xml中的布局已经被添加到ViewGroup root中,如果需要添加到另外的地方,这种方法是不可行的
 @Nullable
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
            @Nullable Bundle savedInstanceState) {
            View view = inflater.inflate(layoutRes, container, false);
        return view ;
    }
public class TestViewInflaterFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.activity_main, container, true);
    }
}
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        supportFragmentManager.beginTransaction().add(R.id.fl_container, TestViewInflaterFragment()).commit()
    }
}
 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.test.demo/com.test.demo.MainActivity}: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
                                                                                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
                                                                                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
                                                                                  at android.app.ActivityThread.-wrap11(Unknown Source:0)
                                                                                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
                                                                                  at android.os.Handler.dispatchMessage(Handler.java:105)
                                                                                  at android.os.Looper.loop(Looper.java:164)
                                                                                  at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                                  at java.lang.reflect.Method.invoke(Native Method)
                                                                                  at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
                                                                               Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
                                                                                  at android.view.ViewGroup.addViewInner(ViewGroup.java:4915)
                                                                                  at android.view.ViewGroup.addView(ViewGroup.java:4746)
                                                                                  at android.view.ViewGroup.addView(ViewGroup.java:4686)
                                                                                  at android.view.ViewGroup.addView(ViewGroup.java:4659)
                                                                                  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1425)
                                                                                  at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1740)
                                                                                  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1809)
                                                                                  at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:799)
                                                                                  at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2580)
                                                                                  at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2367)
                                                                                  at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2322)
                                                                                  at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2229)
                                                                                  at android.support.v4.app.FragmentManagerImpl.dispatchStateChange(FragmentManager.java:3221)
                                                                                  at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:3171)
                                                                                  at android.support.v4.app.FragmentController.dispatchActivityCreated(FragmentController.java:192)
                                                                                  at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:560)
                                                                                  at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:177)
                                                                                  at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1333)
                                                                                  at android.app.Activity.performStart(Activity.java:6992)
                                                                                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2780)
                                                                                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892) 
                                                                                  at android.app.ActivityThread.-wrap11(Unknown Source:0) 
                                                                                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593) 
                                                                                  at android.os.Handler.dispatchMessage(Handler.java:105) 
                                                                                  at android.os.Looper.loop(Looper.java:164) 
                                                                                  at android.app.ActivityThread.main(ActivityThread.java:6541) 
                                                                                  at java.lang.reflect.Method.invoke(Native Method) 
                                                                                  at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
                                                                                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 
  View performCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        if (mChildFragmentManager != null) {
            mChildFragmentManager.noteStateNotSaved();
        }
        mPerformedCreateView = true;
        return onCreateView(inflater, container, savedInstanceState);
    }
//-----------FramgnetManager---------------
 void moveToState(Fragment f, int newState, int transit, int transitionStyle,
            boolean keepActive) {   
                //省略部分代码
                  ``` 
            switch (f.mState) {
                  //省略部分代码
                  ``` 
                case Fragment.CREATED:
                    // This is outside the if statement below on purpose; we want this to run
                    // even if we do a moveToState from CREATED => *, CREATED => CREATED, and
                    // * => CREATED as part of the case fallthrough above.
                    ensureInflatedFragmentView(f);

                    if (newState > Fragment.CREATED) {
                        if (DEBUG) Log.v(TAG, "moveto ACTIVITY_CREATED: " + f);
                        if (!f.mFromLayout) {
                            ViewGroup container = null;
                            if (f.mContainerId != 0) {
                                if (f.mContainerId == View.NO_ID) {
                                    throwException(new IllegalArgumentException(
                                            "Cannot create fragment "
                                                    + f
                                                    + " for a container view with no id"));
                                }
                           //首先根据我们传入的mContainerId(对于本案例来说就是R.id.fl_container)找到container 
                                container = (ViewGroup) mContainer.onFindViewById(f.mContainerId);
                                if (container == null && !f.mRestored) {
                                    String resName;
                                    try {
                                        resName = f.getResources().getResourceName(f.mContainerId);
                                    } catch (NotFoundException e) {
                                        resName = "unknown";
                                    }
                                    throwException(new IllegalArgumentException(
                                            "No view found for id 0x"
                                            + Integer.toHexString(f.mContainerId) + " ("
                                            + resName
                                            + ") for fragment " + f));
                                }
                            }
                            f.mContainer = container;
                          //这个f.mView就是我们自己在onCreateView方法中创建返回的View
                            f.mView = f.performCreateView(f.performGetLayoutInflater(
                                    f.mSavedFragmentState), container, f.mSavedFragmentState);
                            if (f.mView != null) {
                                f.mInnerView = f.mView;
                                f.mView.setSaveFromParentEnabled(false);
                                if (container != null) {
                            //关键地方,在这里会将xml创建的view添加到container
                                    container.addView(f.mView);
                                }
                          //省略部分代码
                            ``` 
                    }

                   //省略部分代码
                  ``` 
            }
    }
 void ensureInflatedFragmentView(Fragment f) {
        if (f.mFromLayout && !f.mPerformedCreateView) {
            f.mView = f.performCreateView(f.performGetLayoutInflater(
                    f.mSavedFragmentState), null, f.mSavedFragmentState);
            if (f.mView != null) {
                f.mInnerView = f.mView;
                f.mView.setSaveFromParentEnabled(false);
                if (f.mHidden) f.mView.setVisibility(View.GONE);
                f.onViewCreated(f.mView, f.mSavedFragmentState);
                dispatchOnFragmentViewCreated(f, f.mView, f.mSavedFragmentState, false);
            } else {
                f.mInnerView = null;
            }
        }
    }
上一篇下一篇

猜你喜欢

热点阅读