dzwillpower
7/20/2012 - 7:16 AM

解决Android下面TextView显示长度的问题 通过计算每个字符的宽度

解决Android下面TextView显示长度的问题 通过计算每个字符的宽度

/**
	 * 
	 * @param v 需要处理的textview
	 * @param content  要处理的类容
	 * @param show_len 需要显示的长度
	 * @return
	 */
	public static String dealDetailString(TextView v,String content,float show_len){
		TextPaint tpaint =v.getPaint();
		String temp="";
		if(content!=null){
			temp=content.replaceAll("\n", " ").replaceAll("\b", " ");
		}
		String str_content=(content==null?"":temp);
		float len=0;
		int s_len=0;
		float totallength=0;
		if(str_content!=null&&str_content!=""){
			len = tpaint.measureText(str_content);
			totallength=tpaint.measureText(str_content);
			System.out.println("==================== len: "+len);
			s_len=str_content.length();
		}
		for(int i=0;i<s_len&&len>show_len;i++){
			str_content=str_content.substring(0, str_content.length()-1);
			len = tpaint.measureText(str_content);
		}
		if(totallength>show_len)
		{
		return str_content+"...";
		}
		else
		{
			return str_content;
		}
	}