仿微信朋友圈动态内容全文显示与收起实现

前段时间在做项目的时候,产品有一个需求,要求动态的内容如果超过5行的话需要将超过5行的内容进行隐藏,点击全文的时候进行展示,点击收起进行隐藏,类似微信朋友圈的效果,当时在网上查找相关的资料发现了有一个博主(刘永雷)的一个案例,但是这种方式存在一些bug,例如会出现错位的问题,故采用如下方式进行实现:

当时在做这个功能的时候就发现,难点是获取文字对应的行数,同时发现以下方式获取的行数不准确:

/**
* 获取TextView的行数
*
* @param context
* @param textView
* @return
*/
public static int getLineNumber(Context context, TextView textView) {
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
int width = wm.getDefaultDisplay().getWidth();

int widthMeasure = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY);
int heightMeasure = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
textView.measure(widthMeasure, heightMeasure);
int lineHeight = textView.getLineHeight();
int lineNumber = textView.getMeasuredHeight() / lineHeight;
return lineNumber;
}

/

以下方式获取的是正确的:

/**
* 计算出该TextView中文字的长度(像素)

* @param textView
* @param text
* @return
*/
public static int getTextViewLength(TextView textView, String text) {
TextPaint paint = textView.getPaint();
// 得到使用该paint写上text的时候,像素为多少
int textLength = (int) paint.measureText(text);
return textLength;
}


/**
* 根据手机的分辨率从 dp 的单位 转成为 px(像素)
*/
public static int dip2px(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}


/**
* 根据手机的分辨率从 px(像素) 的单位 转成为 dp
*/
public static int px2dip(Context context, float pxValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}


private int availableTextWidth;

// 获取屏幕的宽度减去TextView两边的间距,得到TextView的有效宽度(两行)
availableTextWidth = (MainActivity.screenWidth - dip2px(mContext, 28)) * 2;// 28是TextView的左边距和右边距之和

tv_content.setText(content);
if (availableTextWidth < getTextViewLength(tv_content, content)) {
tv_showorhide.setVisibility(View.VISIBLE);
if (!getItem(position).isShow) {
tv_showorhide.setText("全文");
tv_content.setEllipsize(TruncateAt.END);
tv_content.setMaxLines(2);
} else {
tv_content.setMaxLines(1024);
tv_showorhide.setText("收起");
}
tv_showorhide.setOnClickListener(new View.OnClickListener() {


@Override
public void onClick(View v) {
if (tv_showorhide.getText().equals("全文")) {
tv_content.setMaxLines(1024);
tv_showorhide.setText("收起");
getItem(position).isShow = true;
} else {
tv_showorhide.setText("全文");
tv_content.setMaxLines(2);
getItem(position).isShow = false;
}
}
});
} else {
tv_showorhide.setVisibility(View.GONE);
}


这段代码是从Adapter中抽取出来的,即使使用布局复用,也不会出现错位现象。


注:初次写博客,写得有点乱,忘各位见谅,还请大家灵活应用。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值