2013-07-17 68 views
2

第一種方法:膨脹子視圖的兩種方法有什麼區別嗎?

LinearLayout parent = ...; 
View child = LayoutInflator.inflate(context, parent, true); 

第二種方法:

LinearLayout parent = ...; 
View child = LayoutInflator.inflate(context, null, false); 
parent.addView(child); 

有什麼區別?

回答

1

如果你檢查充氣方法的來源,你會發現:

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); 
    } 
} 

/* ... */ 

// 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); 
} 

所以在你的例子是沒有區別的。

會有在這種情況下

View child = LayoutInflator.inflate(context, parent, false); 

孩子將有相同的LayoutParams父有差別,但它不會被附着所以這將是剛剛獨立的視圖。

0

不同之處在於你的第二個參數,它主要告訴Android哪個視圖是你正在膨脹的視圖的父視圖。

在第一種情況下,視圖將被膨脹到ViewGroup中,該ViewGroup是「父」實例。在第二種情況下,新創建的視圖沒有父項,並且將按原樣膨脹。

1

據Android開發者文檔:

View child = LayoutInflator.inflate(context, parent, true); 

會對孩子添加到父,

View child = LayoutInflator.inflate(context, null, false); 

不會。

你可以檢查出的參考:android.view.ViewGroup.inflate

0

是 如果真 - :是否充氣層次結構應附着在根參數?

if False - 如果爲false,則root僅用於爲XML中的根視圖創建LayoutParams的正確子類。

這個參數一般用於我們不想使用Adapter類在Listview中添加行的情況 我們希望通過視圖或佈局來製作他們具有子視圖的行,在這種情況下我們使用它。

0

假設您已撥打context資源ID進行膨脹,這非常令人困惑。有以下區別:

佈局資源頂層的佈局參數的使用,取決於parent佈局參數。在第二種情況下,這些佈局參數將不會被應用;

0

source code如下:

471     if (root != null) { 
472      if (DEBUG) { 
473       System.out.println("Creating params from root: " + 
474         root); 
475      } 
476      // Create layout params that match root, if supplied 
477      params = root.generateLayoutParams(attrs); 
478      if (!attachToRoot) { 
479       // Set the layout params for temp if we are not 
480       // attaching. (If we are, we use addView, below) 
481       temp.setLayoutParams(params); 
482      } 
483     } 
484 
485     if (DEBUG) { 
486      System.out.println("-----> start inflating children"); 
487     } 
488     // Inflate all children under temp 
489     rInflate(parser, temp, attrs, true); 
490     if (DEBUG) { 
491      System.out.println("-----> done inflating children"); 
492     } 
493 
494     // We are supposed to attach all the views we found (int temp) 
495     // to root. Do that now. 
496     if (root != null && attachToRoot) { 
497      root.addView(temp, params); 
498     } 
499 
500     // Decide whether to return the root that was passed in or the 
501     // top view found in xml. 
502     if (root == null || !attachToRoot) { 
503      result = temp; 
504     } 

從線471〜482,將設置兒童的佈局PARAMS查看新創建PARAMS其匹配父視圖。

從第496行到第498行,父級添加子視圖和佈局參數。

所以區別在於是否設置了子視圖的佈局參數

相關問題