在ViewGroup中以编程方式添加子视图

时间:2014-06-02 03:34:19

标签: android viewgroup

我正在创建一个自定义ViewGroup,它可以像GridView一样工作,但我在添加和定位子视图时遇到一些困难(渲染后视图为空白)。

这是我的自定义ViewGroup:

public class BoardView extends ViewGroup {


    private static final int mCols = 5;
    private static final int mRows = 7;

    private Context mContext;
    private Integer[] mNumbers;
    private Integer mRightOption;
    private Integer mSize;

    public BoardView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        mNumbers = randomNumbers(); // fill the array with 35 random numbers
    }

    // ViewGroup methods

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        if (mNumbers == null || mNumbers.length == 0)
            return;

        Log.d("BoardView", String.format("left: %s  top: %s  right: %s  bottom: %s", left, top, right, bottom));

        int counter = 0;

        removeAllViews();

        for (int c = 0; c < mCols; c++) {
            for (int r = 0; r < mRows; r++) {
                final int currentNumber = mNumbers[counter];

                LayoutParams params = new LayoutParams(mSize, mSize);

                final int viewLeft = left + (c * mSize);
                final int viewTop = top + (r * mSize);
                final int viewRight = right - ((mCols - (c + 1)) * mSize);
                final int viewBottom = bottom - ((mRows - (r + 1)) * mSize);

                Log.d("NumberView", String.format("left: %s  top: %s  right: %s  bottom: %s", viewLeft, viewTop, viewRight, viewBottom));

                NumberView numberView = new NumberView(mContext);
                numberView.setLayoutParams(params);
                numberView.setNumber(currentNumber);
                numberView.layout(
                        viewLeft,
                        viewTop,
                        viewRight,
                        viewBottom);

                addView(numberView);

                counter++;
            }
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // Try for a width based on our minimum
        int minw = getPaddingLeft() + getPaddingRight() + getSuggestedMinimumWidth();

        int w = Math.max(minw, MeasureSpec.getSize(widthMeasureSpec));

        // Whatever the width ends up being, ask for a height that would let the pie
        // get as big as it can
        int minh = w + getPaddingBottom() + getPaddingTop();
        int h = Math.min(MeasureSpec.getSize(heightMeasureSpec), minh);

        mSize = w / 5;

        setMeasuredDimension(w, h);
    }

}

它出了什么问题?

0 个答案:

没有答案