4

我正在尝试编写自己的布局类,将它的子级放置在常规网格中。布局本身工作得很好,但我无法让这个布局内的按钮上的文本居中。当我在 LinearLayout 中放置相同的按钮时,按钮文本会根据需要居中,因此故障可能在我的布局中。但是我的布局如何影响文本在其子视图上的重力?我怀疑它与布局参数有关,但我还不知道它是如何工作的。

以下是一些可能与问题相关的代码片段:

我的布局类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>

按钮文本显示在按钮的顶部,而不是应有的中心。为了使文本居中,我必须做什么?

4

1 回答 1

3

好的,我发现了问题:我未能覆盖 onMeasure()。只有当 onMeasure() 在某个时候调用函数 measure() 时,子视图的布局才会起作用。这是一个很好的工作示例http://www.arpitonline.com/blog/2012/07/01/creating-custom-layouts-for-android/。我只是希望自定义布局的官方文档能提到这一点。

于 2012-12-20T22:01:44.150 回答