[Android]TextUtils.ellipsize()截取指定长度字符串(附图文混排)

参考:http://zilla.blog.51cto.com/3095640/984775

效果图:


实现代码:

		
		// 监听布局变化,直接获取显示的长度
		txtDescription.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
			
			@Override
			public void onGlobalLayout() {
				if(availableTextWidth == 0&&txtDescription.getWidth()>0){
					TextPaint paint  = txtDescription.getPaint();
					
					int paddingLeft = txtDescription.getPaddingLeft();
					int paddingRight= txtDescription.getPaddingRight();
					
					int bufferWidth =(int) paint.getTextSize()*3;//缓冲区长度,空出两个字符的长度来给最后的省略号及图片
					// 计算出2行文字所能显示的长度
					availableTextWidth = (txtDescription.getWidth() - paddingLeft - paddingRight) * LINE_COUNT- bufferWidth;
					// 根据长度截取出剪裁后的文字
					String ellipsizeStr = (String) TextUtils.ellipsize(DESCRIPTION, (TextPaint) paint, availableTextWidth, TextUtils.TruncateAt.END);

					String imgTag = "img";
					int start = ellipsizeStr.length();
					int end = start + imgTag.length();
					SpannableStringBuilder ssBuilder = new SpannableStringBuilder(ellipsizeStr+imgTag);
					// 插入图片
					Drawable drawable = getResources().getDrawable(R.drawable.video);
					drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
					ImageSpan imgSpan = new ImageSpan(drawable,ImageSpan.ALIGN_BASELINE);
					ssBuilder.setSpan(imgSpan, start, end, SpannableStringBuilder.SPAN_EXCLUSIVE_EXCLUSIVE);
					txtDescription.setText(ssBuilder);
					
					if(Build.VERSION.SDK_INT>=16){
						txtDescription.getViewTreeObserver().removeOnGlobalLayoutListener(this);
					}else{
						txtDescription.getViewTreeObserver().removeGlobalOnLayoutListener(this);
					}
				}
			}
		});


你可能感兴趣的:(Android)