我们看下重写的系统回调函数onMeasure()(用于测量各个控件距离,父子控件空间大小等):
- @Override
- protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
- int widthMode = MeasureSpec.getMode(widthMeasureSpec);
- int heightMode = MeasureSpec.getMode(heightMeasureSpec);
- int widthSize = MeasureSpec.getSize(widthMeasureSpec);
- int heightSize = MeasureSpec.getSize(heightMeasureSpec);
- int width = calculateLayoutWidth(widthSize, widthMode);
- int height;
- if (heightMode == MeasureSpec.EXACTLY) {
- height = heightSize;
- } else {
- height = getDesiredHeight(itemsLayout);
- if (heightMode == MeasureSpec.AT_MOST) {
- height = Math.min(height, heightSize);
- }
- }
- setMeasuredDimension(width, height);
- }
里面用到了532行calculateLayoutWidth()的方法,就是计算Layout的宽度,在calculateLayoutWidth()这个方法里面调用了
- /**
- * Creates layouts
- * @param widthItems width of items layout
- * @param widthLabel width of label layout
- */
- private void createLayouts(int widthItems, int widthLabel) {
- if (itemsLayout == null || itemsLayout.getWidth() > widthItems) {
- itemsLayout = new StaticLayout(buildText(isScrollingPerformed), itemsPaint, widthItems,
- widthLabel > 0 ? Layout.Alignment.ALIGN_OPPOSITE : Layout.Alignment.ALIGN_CENTER,
- 1, ADDITIONAL_ITEM_HEIGHT, false);
- } else {
- itemsLayout.increaseWidthTo(widthItems);
- }
- if (!isScrollingPerformed && (valueLayout == null || valueLayout.getWidth() > widthItems)) {
- String text = getAdapter() != null ? getAdapter().getItem(currentItem) : null;
- valueLayout = new StaticLayout(text != null ? text : "",
- valuePaint, widthItems, widthLabel > 0 ?
- Layout.Alignment.ALIGN_OPPOSITE : Layout.Alignment.ALIGN_CENTER,
- 1, ADDITIONAL_ITEM_HEIGHT, false);
- } else if (isScrollingPerformed) {
- valueLayout = null;
- } else {
- valueLayout.increaseWidthTo(widthItems);
- }
- if (widthLabel > 0) {
- if (labelLayout == null || labelLayout.getWidth() > widthLabel) {
- labelLayout = new StaticLayout(label, valuePaint,
- widthLabel, Layout.Alignment.ALIGN_NORMAL, 1,
- ADDITIONAL_ITEM_HEIGHT, false);
- } else {
- labelLayout.increaseWidthTo(widthLabel);
- }
- }
- }
