需求是这样的:
在应用程序的详情介绍时,有评论的版块,该页评论最多显示5条,而每条最大字数是140个字符,每条评论可能根据字数不同,所占据的高度也不一样,如有的是1行,有的是2、3行,且评论可以翻页。
图片效果如下:
如何解决这样的问题呢?
首先必须知道的是评论控件不要固定不变,而是需要动态计算并动态添加到显示面板中的。
下面通过实例来说一下。
1.定义布局
定义布局的时候,可以用AbsoluteLayout,因为高度是动态量取的,所以具体坐标是可以求得的。参考如下:
android:layout_width="1386px"
android:layout_height="wrap_content"
android:layout_marginTop="60px"
android:id="@+id/comment_content">
该布局文件宽度设置不变,高度根据内容填充。只需将这个布局方在需要显示评论内容的地方。2.显示数据
显示数据,需要根据数据来计算高度,首先把数据设置到控件中,然后通过View.measure(int widthMeasureSpec,int heightMeasureSpec)量取高度,并为该View设置坐标。参考代码:
/**
* 初始化、动态计算高度
*/
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++) {
if (null != mCommentCache && !mCommentCache.empty()) {
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 = currentHeight
+ comment_temp.getMeasuredHeight();
comment_end_index+