子级TextView的重力不适用于自定义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);
    }
}
...
}

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的左下角对齐。


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);
}
链接地址: http://www.djcxy.com/p/84755.html

上一篇: Gravity of a child TextView does not work with custom ViewGroup

下一篇: Cannot Resolve