自定义TextView控件



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");


运行效果



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值