我正在尝试编写自己的布局类,将它的子元素放置在规则的网格中。 布局本身运行良好,但我无法让此布局内按钮上的文本居中。 当我在 LinearLayout 中放置相同的按钮时,按钮文本根据需要居中,因此故障可能在我的布局中。 但是我的布局如何影响文本在其 subview 上的重力?我怀疑它与布局参数有关,但我真的不知道它是如何工作的。
以下是一些可能与问题相关的代码 fragment :
我的布局类 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>
按钮文本显示在按钮的顶部,而不是应有的中心位置。 我需要做什么才能将文本放到中心?
最佳答案
好的,我发现了问题:我未能覆盖 onMeasure()。仅当 onMeasure() 在某个时刻调用函数 measure() 时, subview 的布局才会起作用。这是一个很好的工作示例 http://www.arpitonline.com/blog/2012/07/01/creating-custom-layouts-for-android/ . 我只希望自定义布局的官方文档能提到这一点。
关于Android自定义布局引力,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13962835/