2017-02-16 17 views
0

容器是LinearLayout中,如何通過代碼添加分隔視圖

<LinearLayout 
     android:id="@+id/container" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:orientation="vertical"> 

在代碼中,我想補充意見:

final LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

// add alpha view to container view 
View alphaView = inflater.inflate(R.layout.item_info_alpha, null, false); 
container.addView(alphaView); 

// add divider view to container view 
container.addView(inflater.inflate(R.layout.item_divider, null, false)); 

// add beta view to container view 
View betaView = inflater.inflate(R.layout.item_info_beta, null, false); 
container.addView(betaView); 

// add divider view to container view 
container.addView(inflater.inflate(R.layout.item_divider, null, false)); 

item_divider.xml

<?xml version="1.0" encoding="utf-8"?> 
<View xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="8dp" 
    android:background="#F2F2F4" /> 

添加代碼時分隔符不可見。

如何在將視圖添加到線性佈局時使此分隔線可見?

爲什麼當我們通過xml添加查看,它不會疊加在LinearLayout中?

回答

1

您可以簡單地這樣做:

container.addView(inflater.inflate(R.layout.item_divider, null)); 

或者試試這個代碼:

 View view = new View(YOUR_CONTEXT); //getContext() for example 
     int hight = 8; 
     LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, hight); 
     view.setLayoutParams(params); 
     view.setBackgroundColor(Color.parseColor("#F2F2F4")); 
     container.addView(view); 
+0

container.addView(inflater.inflate(R.layout.item_divider,null));將不起作用 – purplebee

+0

@purplebee它會,請參閱文檔:'https://developer.android.com/reference/android/view/LayoutInflater.html#inflate(int,android.view.ViewGroup)' –

0

替換inflater.inflate(..)truefalse並沒有專門調用addView(..)LinearLayout

LayoutInflater的用途是不必手動設置LayoutParams

如果您使用attachToRoot=falseView充氣,則使用root的LayoutParams創建新的View,然後丟棄。

如果attachToRoot=true,LayoutParams被保留,並且新的View被附加到rootView,在你的情況下LinearLayout

+0

您試圖回答「爲什麼」的一部分,但我沒有得到它。 – purplebee

+0

好的,每個View都有一組名爲LayoutParams的變量,它們決定將視圖放置在屏幕上的位置,它有多大,等等。如果您只是調用addView(),則視圖被添加但沒有LayoutParams,因此它不會知道如何顯示自己 – CrowsNet

+0

來解決這個問題,要麼顯式調用setLayoutParams(),要麼使用LayoutInflater.inflate(layoutId,parent,true)<=真正代表「將新的虛擬視圖附加到父視圖組,並且還請使用LayoutParams我的父母知道我想如何在屏幕上看。「 – CrowsNet