子を通常のグリッドに配置する独自のレイアウトクラスを作成しようとしています。レイアウト自体はうまく機能しますが、このレイアウト内のボタンのテキストを中央に配置することができません。同じボタンを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>
ボタンのテキストは、ボタンの中央ではなく、ボタンの上部に表示されます。テキストを中央に表示するにはどうすればよいですか?