package com.lin.test; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Paint.FontMetrics; import android.util.AttributeSet; import android.util.Log; import android.widget.TextView; /** * 新闻内容简介,一般用一行或两行显示,一行显示不下的用两行显示</br> * 后面再加上查看次数,查看次数永远固定在第二行靠右显示 * * @author linchunda * */ public class MyTextView extends TextView { private Context context; private AttributeSet set; private String concise;//新闻内容简介 private String count;//查看次数 public MyTextView(Context context, AttributeSet set) { super(context, set); this.context = context; this.set = set; } public void setConcise(String concise) { this.concise = concise; } public void setCount(String count) { this.count = count + "人查看"; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); Paint paint = getPaint(); //自定义的TextView宽度 int width = getWidth(); FontMetrics fontMetrics = paint.getFontMetrics(); //每行字符串数 int length = width / (int) getTextSize(); Log.i("MyTextView", "length===>" + length); //每行的高度 int lineHeight = (int) (fontMetrics.descent - fontMetrics.ascent); if (concise.length() > length) { String start = concise.substring(0, length+1); canvas.drawText(start, 0, lineHeight, paint);//显示第一行 Log.i("MyTextView", "start===>" + start); concise = concise.replace(start, "");//去掉第一行内容后的新闻简介 if(concise.length()>length - count.length() - 5){ //第二行内容长度超length - count.length() - 5,将进行截取,否则不用截取啦 concise = concise.substring(0, length - count.length() - 5); } Log.i("MyTextView", "start2===>" + concise); canvas.drawText(concise, 0, lineHeight * 2+4, paint);//打印第二行内容 canvas.drawText(count, (int) getTextSize() * (length - count.length()+2), lineHeight * 2+4, paint);//在第二行后面显示查看次数 } else { canvas.drawText(concise, 0, lineHeight, paint); canvas.drawText(count, (int) getTextSize() * (length - count.length()+2), lineHeight * 2+4, paint); } } }
<com.lin.test.MyTextView android:id="@+id/textview_4" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/lightgray" android:lines="2" android:textColor="@color/black" android:paddingBottom="5dp"/>
textview_4 = (MyTextView) findViewById(R.id.textview_4);
textview_4.setConcise(ToSBC(content));
textview_4.setCount("20");
运行效果