Страница 1 из 1

ScrollView не показывает эллементы

Добавлено: 04 фев 2014, 05:15
Sirelon
Здравствуйте.
Столкнулся с такой проблемой: у меня есть слой, в котором расположены кнопочки.. Много кнопочек.. вот хотелось сделать, чтобы экран прокручивался.
Сразу скажу - кнопки добавляются в слой, который реализован UI паттерном DashBoard. Код создания слоя безбожно скопирован с данной статьи на хабре
Так вот - при добавлении этого слоя в ScrollView ВООБЩЕ ничего не отображается..
Я так понимаю тут дело в переопределлённом методе

Код: Выделить всё

onMeasure
, где задаются высота и ширина вьюхи. (там считается предпочтительные знаечения, исходя из размеров экрана и самой вьюхи).
Но хоть убейте, не понимаю, почему не отрисовывается слой в ScrollView..
Помогите, пожалуйста :cry:

Re: ScrollView не показывает эллементы

Добавлено: 04 фев 2014, 05:27
Sirelon
хотя нет.. таки то что мне мешает сидит в методе onLayout()
отступы создает.. Блин..

Код: Выделить всё

@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) {
			int width = r - l;
	        int height = b - t;

	        final int count = getChildCount();

	        // Calculate the number of visible children.
	        int visibleCount = 0;
	        for (int i = 0; i < count; i++) {
	            final View child = getChildAt(i);
	            if (child.getVisibility() == GONE) {
	                continue;
	            }
	            ++visibleCount;
	        }

	        if (visibleCount == 0) {
	            return;
	        }

	        // Calculate what number of rows and columns will optimize for even horizontal and
	        // vertical whitespace between items. Start with a 1 x N grid, then try 2 x N, and so on.
	        int bestSpaceDifference = Integer.MAX_VALUE;
	        int spaceDifference;

	        // Horizontal and vertical space between items
	        int hSpace = 0;
	        int vSpace = 0;

	        int cols = 1;
	        int rows;

	        while (true) {
	            rows = (visibleCount - 1) / cols + 1;

	            hSpace = ((width - mMaxChildWidth * cols) / (cols + 1));
	            vSpace = ((height - mMaxChildHeight * rows) / (rows + 1));

	            spaceDifference = Math.abs(vSpace - hSpace);
	            if (rows * cols != visibleCount) {
	                spaceDifference *= UNEVEN_GRID_PENALTY_MULTIPLIER;
	            }

	            if (spaceDifference < bestSpaceDifference) {
	                // Found a better whitespace squareness/ratio
	                bestSpaceDifference = spaceDifference;

	                // If we found a better whitespace squareness and there's only 1 row, this is
	                // the best we can do.
	                if (rows == 1) {
	                    break;
	                }
	            } else {
	                // This is a worse whitespace ratio, use the previous value of cols and exit.
	                --cols;
	                rows = (visibleCount - 1) / cols + 1;
	                hSpace = ((width - mMaxChildWidth * cols) / (cols + 1));
	                vSpace = ((height - mMaxChildHeight * rows) / (rows + 1));
	                break;
	            }

	            ++cols;
	        }

	        // Lay out children based on calculated best-fit number of rows and cols.

	        // If we chose a layout that has negative horizontal or vertical space, force it to zero.
	        hSpace = Math.max(0, hSpace);
	        vSpace = Math.max(0, vSpace);

	        // Re-use width/height variables to be child width/height.
	        width = (width - hSpace * (cols + 1)) / cols;
	        height = (height - vSpace * (rows + 1)) / rows;

	        int left, top;
	        int col, row;
	        int visibleIndex = 0;
	        for (int i = 0; i < count; i++) {
	            final View child = getChildAt(i);
	            if (child.getVisibility() == GONE) {
	                continue;
	            }

	            row = visibleIndex / cols;
	            col = visibleIndex % cols;

	            left = hSpace * (col + 1) + width * col;
	            top = vSpace * (row + 1) + height * row;

	            child.layout(left, top,
	                    (hSpace == 0 && col == cols - 1) ? r : (left + width),
	                    (vSpace == 0 && row == rows - 1) ? b : (top + height));
	            ++visibleIndex;
	        }
	    }

Re: ScrollView не показывает эллементы

Добавлено: 04 фев 2014, 16:50
Sirelon
В общем проблему нашел.
при методе onMeasure расчитывается высота этим кодом

Код: Выделить всё

  int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
                MeasureSpec.getSize(heightMeasureSpec), MeasureSpec.AT_MOST);
и почему то принимает значение -2147483648!!!

Выход: поменять в аргументах MeasureSpec.AT_MOST на MeasureSpec.UNSPECIFIED. Подробнее тут прочитал.
В отображаемых вьюхах установить android:minHeight ну или android:height.

Ну и пока всё, к чему дошел. Скролл появился, что не может не радовать. Но отображение ещё не то, что надо. Разбираюсь дальше.