android计算控件距离顶部高度,Android布局之View.measure()动态量取高度并设置布局--(例:动态计算评论高度并显示)...

本文介绍了在Android应用中如何动态计算评论控件的高度,以适应不同字数的评论。通过使用`View.measure()`方法,根据每条评论的字数动态调整布局,并在评论区域展示,同时实现了评论的翻页功能,确保布局自适应并保持良好的视觉效果。
摘要由CSDN通过智能技术生成

需求是这样的:

在应用程序的详情介绍时,有评论的版块,该页评论最多显示5条,而每条最大字数是140个字符,每条评论可能根据字数不同,所占据的高度也不一样,如有的是1行,有的是2、3行,且评论可以翻页。

图片效果如下:

0818b9ca8b590ca3270a3433284dd417.png

如何解决这样的问题呢?

首先必须知道的是评论控件不要固定不变,而是需要动态计算并动态添加到显示面板中的。

下面通过实例来说一下。

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+

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值