我試圖做一個類似於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