子项的重力TextView不适用于自定义ViewGroup

时间:2015-09-25 13:07:22

标签: android android-layout android-view android-adapter android-viewgroup

我有以下课程:

public class MyGridView extends ViewGroup {
...
@Override
public void onSizeChanged(int xNew, int yNew, int xOld, int yOld) {

super.onSizeChanged(xNew, yNew, xOld, yOld);
// do calculations for drawing bounds of child views
}

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
    View child;
Rect rect;

for (int i=0; i < getChildCount(); i++) {
    child = getChildAt(i);

    rect = getBoundsAtChildIndex(i)
        child.layout(rect.left, rect.top, rect.right, rect.bottom);
    }
}
...
}

AND

public class MyAdapter {

public void setMyGridView(MyGridView myGridView) {

// add a single TextView to my grid view
textView = createTextView(context);
addTextViewToGrid(textView);
container.add(textView);
}

private TextView createTextView(Context context) {
    TextView textView = new TextView(context);

    textView.setText("1");
    textView.setTextColor(0xffffffff);

    textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12f);
    textView.setTypeface(typeface);

    textView.setGravity(Gravity.CENTER | Gravity.FILL);
// textView.setGravity(Gravity.RIGHT); // other tries to see gravity
// textView.setGravity(Gravity.FILL);

    return textView;
}

private void addTextViewToGrid(TextView textView) {
    myGridViewPtr.addView(textView, ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT);
}
...
}

我创建了一个自定义网格视图和适配器,其子项在屏幕上绘制到正确的大小和位置。但是,没有观察到它们在createTextView()中设置的重力。

我可以将背景图像设置为textView并看到它填充网格中的空间。

相比之下,textView中的文本总是在其左上角绘制,并始终保持在我设置为12sp的文本大小,而不是使用Gravity.FILL缩放以适合。

优选地,文本将缩放以适合文本视图并使其居中。

修改

我在ViewGroup中为onMeasure()添加了以下方法:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    int width = getMeasuredWidth();
    int height = getMeasuredHeight();

    doUpdateOnSizeChanged(width, height);

    for (int i = 0; i < getChildCount(); i++)
        getChildAt(i).measure((int) viewDim.x, (int) viewDim.y);

    setMeasuredDimension(width, height);
}

孩子们的身高和宽度应该相同。 ViewGroup的android示例代码比我要求的更复杂。例如,我没有得到所有孩子宽度,身高的最大值。

对于我的onMeasure(),ViewDim中的子宽度,高度是宽度,在doUpdateOnSizeChanged中计算的高度整数小于getMeasuredWidth,getMeasuredHeight。

现在结果是文本在TextView的左下角对齐。

1 个答案:

答案 0 :(得分:1)

onMeasure需要进行微小修正,基本上需要依赖MeasureSpec:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

    int width, height;
    int cWidth1, cHeight1;

    width = MeasureSpec.getSize(widthMeasureSpec);
    height = MeasureSpec.getSize(heightMeasureSpec);

    doUpdateOnSizeChanged(width, height);


    cWidth1 = (int)viewDim.x; cHeight1 = (int)viewDim.y;

    measureChildren(MeasureSpec.makeMeasureSpec(cWidth1, MeasureSpec.EXACTLY),
            MeasureSpec.makeMeasureSpec(cHeight1, MeasureSpec.EXACTLY));

    setMeasuredDimension(width, height);
}