Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

View.measure 實戰:動態量取評論高度並排版分頁

編輯:關於 Android 程式設計

需求

應用詳情頁有一塊評論區,最多展示 5 條,每條限 140 字。由於字數不同,每條評論實際佔的高度也不一樣——可能一行,也可能三四行,並且支持翻頁。

效果如下:

要點很明確:評論控件不能寫死高度,必須先量、後排。

一、佈局

因為高度動態計算,用 AbsoluteLayout 反而省事——每個子 View 的坐標都能算出來。外層容器寬度固定、高度按內容填充,放到需要展示評論的位置即可。

二、動態量高並擺放

核心三步:先把數據灌進控件,再調 View.measure(widthMeasureSpec, heightMeasureSpec) 量出高度,最後按累加的偏移量設置坐標。

int width = MeasureSpec.makeMeasureSpec(1386, MeasureSpec.EXACTLY);
int height = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);

寬度用 EXACTLY 表示「就這麼寬」,高度用 UNSPECIFIED 表示「你想多高就多高」,這樣 getMeasuredHeight() 拿到的才是內容真實高度。

public void initCommentView() {
    record_temp = new CommentRecord();
    mPositionRecord = new ArrayList<>();
    mHeightRecord = new ArrayList<>();

    int currentHeight = 0;
    int maxNum = cachedComments.size();
    int sum = 0;

    for (int i = comment_begin_index; i < maxNum; i++) {
        CommentSimpleView comment_temp;
        if (mCommentCache != null && !mCommentCache.isEmpty()) {
            comment_temp = mCommentCache.pop();   // 複用對象
        } else {
            comment_temp = new CommentSimpleView(mContext);
        }
        mCommentUI.add(comment_temp);
        comment_temp.setData(cachedComments.get(i));
        comment_temp.measure(width, height);      // 關鍵:先量

        if (MAX_COMMENT_HEIGHT > currentHeight) {
            comment_content.addView(comment_temp,
                    new AbsoluteLayout.LayoutParams(1386,
                            comment_temp.getMeasuredHeight(),   // 用量出的高度
                            0, FIRST_COMMENT_INTERVAL + currentHeight));
            mPositionRecord.add(FIRST_COMMENT_INTERVAL + currentHeight);
            mHeightRecord.add(comment_temp.getMeasuredHeight());
            currentHeight += comment_temp.getMeasuredHeight();
            comment_end_index++;
            sum++;
            comment_temp.show_Divider();  // 前 4 條帶分隔線
            if (sum == 5) {
                comment_temp.hide_Divider();
            }
        }

        if (MAX_COMMENT_HEIGHT < currentHeight) {
            compareHeight = 1;   // 超出一點,說明最後一條要裁
            isEnd = false;
            RelativeLayout.LayoutParams rl =
                    (RelativeLayout.LayoutParams) comment_content.getLayoutParams();
            rl.setMargins(0, 60, 0, 0);
            rl.width = 1386;
            rl.height = MAX_COMMENT_HEIGHT + 20;
            comment_content.setLayoutParams(rl);
            break;
        }

        if (MAX_COMMENT_HEIGHT == currentHeight) {
            compareHeight = 0;   // 剛好填滿
            isEnd = (maxNum == comment_end_index);
            comment_pagedown.setFocusStatus(!isEnd);
        }
    }

    record_temp.setHeightRecord(mHeightRecord);
    record_temp.setPositionRecord(mPositionRecord);
    record_temp.setBegin_index(comment_begin_index);
    record_temp.setEnd_index(comment_end_index);

    if (MAX_COMMENT_HEIGHT > currentHeight) {
        isEnd = true;
        comment_pagedown.setFocusStatus(false);
    }
}

compareHeight 這個標志很關鍵:0 表示這一頁剛好填滿,1 表示最後一條被擠出去了。翻頁時兩種情況的起始下標算法不同。

三、翻頁時判斷是否還有剩餘空間

private boolean hasExtraSpace() {
    if (cachedComments != null && cachedComments.size() - comment_end_index >= 5) {
        return false;   // 剩下的評論超過一頁,不可能有空間
    }

    int beginIndex = (compareHeight == 1) ? comment_end_index : comment_end_index + 1;
    int maxSize = cachedComments.size();
    int HeightSum = 0;

    for (int i = beginIndex; i < maxSize; i++) {
        CommentSimpleView comment_temp = new CommentSimpleView(mContext);
        comment_temp.setData(cachedComments.get(i));
        comment_temp.measure(width, height);
        HeightSum += comment_temp.getMeasuredHeight();
        if (HeightSum > MAX_COMMENT_HEIGHT) {
            break;
        }
    }
    return HeightSum <= MAX_COMMENT_HEIGHT;
}

如果是倒數第二頁,剩余內容不夠填滿,就直接用記錄快照重建,避免再量一遍:

record_temp = mCommentRecord.pop();
int begin = record_temp.getBegin_index();
int end = record_temp.getEnd_index();
List<Integer> position = record_temp.getPositionRecord();
List<Integer> height = record_temp.getHeightRecord();
if (position == null || height == null) {
    return;
}

int m = 0;
for (int i = begin; i <= end; i++) {
    CommentSimpleView comment_temp = mCommentCache.isEmpty()
            ? new CommentSimpleView(mContext) : mCommentCache.pop();
    mCommentUI.add(comment_temp);
    comment_temp.setData(cachedComments.get(i));
    comment_content.addView(comment_temp,
            new AbsoluteLayout.LayoutParams(1386, height.get(m), 0, position.get(m)));
    m++;
    comment_temp.show_Divider();
    if (m == 5) {
        comment_temp.hide_Divider();
    }
}
isEnd = false;
comment_begin_index = begin;
comment_end_index = end;

四、上下頁點擊處理

public class comment_pageup_click implements OkButtonViewClick {
    @Override
    public void onOkButtonViewClick() {
        if (currentPage == 1) {
            comment_pageup.setFocusStatus(false);
            return;
        }
        currentPage--;
        comment_content.removeAllViews();
        while (!mCommentUI.isEmpty()) {
            mCommentCache.push(mCommentUI.remove(0));   // 控件回收入池
        }
        showPageUp();
        comment_pagedown.setFocusStatus(true);
    }
}

class comment_pagedown_click implements OkButtonViewClick {
    @Override
    public void onOkButtonViewClick() {
        if (isEnd) {
            comment_pagedown.setFocusStatus(false);
            return;
        }
        mCommentRecord.push(record_temp);   // 當前頁狀態入棧
        currentPage++;
        if (!hasExtraSpace()) {
            if (compareHeight == 1) {
                comment_begin_index = comment_end_index;
                comment_end_index--;
            } else {
                comment_begin_index = comment_end_index + 1;
            }
            if (currentPage % 4 == 0) {
                ParserHelper.getParserHelper().requestComment(1, 30, 9, callback);
            }
            comment_content.removeAllViews();
            while (!mCommentUI.isEmpty()) {
                mCommentCache.push(mCommentUI.remove(0));
            }
            initCommentView();
        } else {
            comment_content.removeAllViews();
            while (!mCommentUI.isEmpty()) {
                mCommentCache.push(mCommentUI.remove(0));
            }
            showLastPage();
        }
        comment_pageup.setFocusStatus(true);
    }
}

每翻到第 4 頁預加載一批數據,是為了避免用戶快速翻頁時出現空白。

五、用棧保存每頁狀態

public class CommentRecord {
    int begin_index;
    int end_index;
    List<Integer> positionRecord;
    List<Integer> heightRecord;

    // getter / setter 省略
}

入棧時記下這一頁的起止下標、每條的高度和 y 坐標;回翻時直接出棧重建,不必重新 measure。這是用空間換時間的典型做法,幾十條評論的量級完全負擔得起。

總結

動態計算、動態佈局在實戰中很常見,關鍵就兩步:先 setData 再 measure 拿到真實高度,然後調用

ViewGroup.addView(View child, LayoutParams params)

把它放到計算好的坐標上。掌握了這條鏈路,凡是「內容高度不確定、需要精確排版」的需求都能套用。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved