Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/229.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android自定义布局重力_Android_Android Layout_Gravity - Fatal编程技术网

Android自定义布局重力

Android自定义布局重力,android,android-layout,gravity,Android,Android Layout,Gravity,我正在尝试编写自己的布局类,将它的子对象放置在一个规则的网格中。 布局本身工作得很好,但我无法使布局中按钮上的文本居中。 当我在线性布局中放置相同的按钮时,按钮文本会按需要居中,因此故障可能在我的布局中。 但是我的布局如何影响文本在其子视图上的重力呢?我怀疑这与布局参数有关,但我还不知道它是如何工作的 以下是一些可能与此问题相关的代码片段: “我的布局”类的布局: public class WeightedGridLayout extends ViewGroup { // ... @Over

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

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

“我的布局”类的布局:

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);
}

}
以下是按钮的属性:

<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()时,子视图的布局才会起作用。这是一个很好的工作示例。 我只希望定制布局的官方文档会提到这一点

<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>