2012-03-26 98 views
1

如果我只想設置父視圖的佈局並仍想保留子佈局設置,我可以以某種方式阻止調用所有Children的佈局方法嗎?Android:擴展布局中的中心Textview

目前我調用parent.layout()和它的所有孩子的寬度和heiht爲零。我不能以某種方式將孩子設置爲FillParent而不是將佈局設置爲ALL? :-(

順便說一句,我的父母爲主要包含Textviews擴展的LinearLayout



編輯: 一些代碼:

myLayout擴展的LinearLayout

myLayout.layout(left, top, right, bottom);     
myLayout.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1)); 

for each child in myLayout do { 
    child.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); 
    if (v instanceof TextView) { 
    ((TextView) v).setGravity(Gravity.CENTER); 
    } 

但孩子還有:
左:0頂:0右:0底部:0

編輯2: 順便說一下:上面的代碼是內部的ViewGroup的onLayout方法。

回答

0

你的孩子的意見沒有得到衡量(因爲你不叫他們的佈局()),所以系統仍然認爲他們是0x0px。

Android使用度量/佈局的雙通道系統。

請參閱開發文檔,看圖紙/佈局序列是如何發生的:http://developer.android.com/guide/topics/ui/how-android-draws.html

你可能想嘗試把他們的layout(),然後設置對孩子的高度/寬度,然後調用requestLayout()

希望有所幫助。

0

您可以在擴展的LinearLayout的onLayout()方法中設置子對象的寬度和高度。例如:

@Override 
protected void onLayout(boolean changed, int l, int t, int r, int b) { 
    super.onLayout(changed, l, t, r, b); 
    int count = getChildCount(); 
    for (int i = 0; i < count; i++) { 
     final View child = getChildAt(i); 
     // set width of every child to FILL_PARENT, and height to WRAP_CONTENT 
     child.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); 
    } 
} 

我不知道爲什麼setGravity()不適合你。可能是你設置重力不是爲了孩子,而是爲了佈局?我可以設置重力,例如在onLayout()

if (child instanceof TextView) { 
    ((TextView) child).setGravity(Gravity.CENTER); 
} 
+0

不起作用。孩子仍然在左邊:0頂部:0右邊:0底部:0 – 2012-04-13 13:06:58