我试图做一个类似于LinearLayout的自定义布局控件,但我希望所有的控件内部包装。这就像LinearLayout,但包装。所以,我从Android的固定网格控件的例子,并开始修改它。它正在工作,但我遇到了问题。自定义布局控件
问题是,当我把按钮放在里面时,文字并没有让我给他们引力或我给的任何参数。在下面的图片中,按钮内部的文本应居中,并在垂直中间,但事实并非如此。
我FixedGridLayout类的来源是:
package com.projects;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
public class FixedGridLayout extends ViewGroup {
int mCellWidth = 160;
int mCellHeight = 120;
public FixedGridLayout(Context context) {
super(context);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int cellWidthSpec = MeasureSpec.makeMeasureSpec(mCellWidth, MeasureSpec.AT_MOST);
int cellHeightSpec = MeasureSpec.makeMeasureSpec(mCellHeight, MeasureSpec.AT_MOST);
int count = getChildCount();
for (int index = 0; index < count; index++) {
final View child = getChildAt(index);
child.measure(cellWidthSpec, cellHeightSpec);
}
int minCount = count > 3 ? count : 3;
setMeasuredDimension(resolveSize(mCellWidth * minCount, widthMeasureSpec),
resolveSize(mCellHeight * minCount, heightMeasureSpec));
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
int cellWidth = mCellWidth;
int cellHeight = mCellHeight;
int columns = (right - left)/cellWidth;
if (columns < 0) {
columns = 1;
}
int x = 0;
int y = 0;
int i = 0;
int count = getChildCount();
for (int index = 0; index < count; index++) {
final View child = getChildAt(index);
child.layout(x, y , x + cellWidth, y + cellHeight);
if (i >= (columns - 1)) {
i = 0;
x = 0;
y += cellHeight;
} else {
i++;
x += cellWidth;
}
}
}
}
我用它来测试布局XML代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.projects.FixedGridLayout android:layout_width="600dp" android:layout_height="300dp">
<Button android:text="Line1 Line2" android:gravity="center_horizontal|center_vertical" />
<Button android:text="Line1 Line2 Line3" android:gravity="center_horizontal|center_vertical" />
<Button android:text="Line1" android:gravity="center_horizontal|center_vertical" />
<Button android:text="Line1" android:gravity="center_horizontal|center_vertical" />
<Button android:text="Line1 Line2" android:gravity="center_horizontal|center_vertical" />
<Button android:text="Line1 Line2 Line3" android:gravity="center_horizontal|center_vertical" />
<Button android:text="Line1" android:gravity="center_horizontal|center_vertical" />
<Button android:text="Line1" android:gravity="center_horizontal|center_vertical" />
</com.projects.FixedGridLayout>
</LinearLayout>
类FixedGridLayout的代码是一个精简,针对我的应用和此问题稍作修改和简化:http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/animation/FixedGridLayout.html
你还没有真正回答我的问题,而是你解决了我的主要问题,所以THX, – darkzangel
Np - 我发现最好尽可能地坚持使用android框架,避免“重新发明轮子”:)避免出现其他问题 – Ken