View.inflate() 和 LayoutInflater.from(this).inflate() 的區別

        llContainer = findViewById(R.id.llContainer);
//       第一種情況下:
        View view = View.inflate(this, R.layout.activity_test, null);
//        inflate(resource, root, root != null);  R.layout.activity_main  null false
        ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
        // 這種情況下 layoutParams 應該爲null,因爲它沒有父親,一個view的LayoutParams,主要是依靠父佈局來決定
        System.out.println("layoutParams : " + layoutParams);
//        因爲沒有父親,所以你獲取view的父親就是爲null
        ViewParent parent = view.getParent();
        //父控件也應該是爲null
        System.out.println("parent : " + parent);
        System.out.println("view : " + view);// android.widget.LinearLayout{113d4dd V.E  意思就是最外層的view爲Linearlayout
//        第二種情況下:
        View view2 = View.inflate(this, R.layout.activity_test, llContainer);
//        inflate(resource, root, root != null);  R.layout.activity_main  llContainer true
        ViewGroup.LayoutParams layoutParams2 = view2.getLayoutParams();
//        這個時候layoutParams不爲空
        System.out.println("layoutParams2 : " + layoutParams2);
//        parent2 也不爲空
        ViewParent parent2 = view2.getParent();
        System.out.println("parent2 : " + parent2);
//        第三種方式:
//      還有一種是想生成layoutParams,但是不想不view加入的ViewGroup中去,比如recycleView的onBindViewHolder
        View view3 = LayoutInflater.from(this).inflate(R.layout.activity_test, llContainer, false);
//        layoutParams3 不爲空
        ViewGroup.LayoutParams layoutParams3 = view3.getLayoutParams();
//        parent3 爲空
        ViewParent parent3 = view3.getParent();
//        android.widget.LinearLayout$LayoutParams@a44f420 parent3 : null
        System.out.println("layoutParams3 : " + layoutParams3 + " parent3 : " + parent3);
發佈了55 篇原創文章 · 獲贊 7 · 訪問量 4259
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章