2012-12-19 41 views
4

我想寫我自己的佈局類,它把孩子放在一個規則的網格。 佈局本身很好地工作,但我無法獲得此佈局中的按鈕上的文本居中。 當我在LinearLayout中放置相同的按鈕時,按鈕文本會根據需要居中,因此錯誤可能在我的佈局中。 但是,我的佈局如何影響其子視圖上文本的嚴重性?我懷疑它與佈局參數有關,但我不知道它是如何工作的。Android自定義佈局重力

這裏有一些代碼段,這可能是相關的問題:

我的佈局類WeightedGridLayout:

public class WeightedGridLayout extends ViewGroup { 

// ... 

@Override 
protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 
    for (int i = 0, N = getChildCount(); i < N; i++) { 
     View c = getChildAt(i);  
     // ... 
     // do some calculation 
     // 
     c.layout(childLeft, childTop, childRight, childBottom); 
    }  
} 

public static class LayoutParams extends ViewGroup.MarginLayoutParams { 
    public Position position = position(0, 0); 
    public Span span = span(1, 1); 
    // Position and Span are local classes which are irrelevant here 

public LayoutParams(Position position, Span span) { 
    super(FILL_PARENT, FILL_PARENT); 
    this.position = position; 
    this.span = span; 
} 
public LayoutParams(Position position) { 
    this(position, span(1,1)); 
} 
public LayoutParams() { 
    this(position(0,0), span(1,1)); 
} 
public LayoutParams(MarginLayoutParams params) { 
    super(params); 
} 
public LayoutParams(LayoutParams that) { 
    super(that); 
    this.position = that.position; 
    this.span = that.span; 
} 
public LayoutParams(Context context, AttributeSet attrs) { 
    super(context, attrs); 
} 

} 

類這樣使用:

WeightedGridLayout grid = (WeightedGridLayout) findViewById(R.id.mainMenu); 
    LayoutInflater inflater = getLayoutInflater(); 
    Button button = (Button)inflater.inflate(R.layout.buttonproperties, null); 
    button.setText("None"); 
    WeightedGridLayout.Position pos = WeightedGridLayout.position(colIdx,rowIdx); 
    WeightedGridLayout.LayoutParams lp = new WeightedGridLayout.LayoutParams(pos); 
    lp.setMargins(5,20,5,20);   
    grid.addView(button, lp); 

這裏有按鈕屬性:

<Button xmlns:android="http://schemas.android.com/apk/res/android" 
    android:background="@drawable/default_button" 
    android:gravity="center" 
    android:textSize="@dimen/text" 
    android:textColor="@color/text" > 
</Button> 

按鈕文本出現在按鈕的頂部,而不是它應該在中間。 爲了讓文字到達中心我需要做些什麼?

回答