前提:公司需求,在图中右侧的tip中,如果数据过长,就在尾部省略。返回的数据是 ("局部多云,不利于健康")
原本是一个TextView,虽然用两个textview最容易实现,但是感觉太low了吧。
于是乎,学了这么久的自定义View 终于派上用场了。
哈哈哈哈嗝。。。。
不说废话,上代码!
CharSequence text = getText(); int width = getWidth(); float textSize = getTextSize(); float textScaleX = getTextScaleX(); int textCount = (int) ((width-getPaddingLeft()-getPaddingRight()) / (textSize+textScaleX)); String[] split = text.toString().split("\n"); LG.e("lmy", "text="+text+",width="+width+",size="+textSize+",textCount="+textCount+",split="+Arrays.toString(split)); StringBuffer buffer=new StringBuffer(); for (int i = 0; i < split.length; i++) { String s = split[i]; if (s.length() > textCount&&textCount>0) { buffer.append(s.substring(0, textCount - 1)); buffer.append("..."); } else { buffer.append(s); } if (i < split.length - 1) { buffer.append("\n"); } } String result = buffer.toString();
首先 ,前面几步的获取我就不多说了。
width-getPaddingLeft()-getPaddingRight() 总的宽度减去左右内边距,没意见吧。
int textCount = (int) ((width-getPaddingLeft()+getPaddingRight()) / (textSize+textScaleX));字体总宽度除以字体的大小加间距
getTextScaleX()这个方法是获取自体间距的
String[] split = text.toString().split("\n"); 这里因为是用\n换行,所以这里在截取一下 对每一行的自体数量做下判断。
for (int i = 0; i < split.length; i++) { String s = split[i]; if (s.length() > textCount&&textCount>0) { buffer.append(s.substring(0, textCount - 1)); buffer.append("..."); } else { buffer.append(s); } if (i < split.length - 1) { buffer.append("\n"); } }
这一部分就是循环判断每一行自体的个数有没有超过最大的限制 有的话就把最后一个字符删除掉用...代替
下面添加\n的时候做了个判断最后一行不会添加,保证字体垂直居中。
调用的话我是在onLayout里调用的,在setText里调用的话有可能宽度测试不准所以在onLayout里调用
下面附上全部代码和效果图
效果图
全部代码
public class CustomTextView extends TextView{ public CustomTextView(Context context) { super(context); } public CustomTextView(Context context, AttributeSet attrs) { super(context, attrs); } public CustomTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { setText(updateTip().toString()); } private String updateTip(){ CharSequence text = getText(); int width = getWidth(); float textSize = getTextSize(); float textScaleX = getTextScaleX(); int textCount = (int) ((width-getPaddingLeft()+getPaddingRight()) / (textSize+textScaleX)); String[] split = text.toString().split("\n"); LG.e("lmy", "text="+text+",width="+width+",size="+textSize+",textCount="+textCount+",split="+Arrays.toString(split)); StringBuffer buffer=new StringBuffer(); for (int i = 0; i < split.length; i++) { String s = split[i]; if (s.length() > textCount&&textCount>0) { buffer.append(s.substring(0, textCount - 1)); buffer.append("..."); } else { buffer.append(s); } if (i < split.length - 1) { buffer.append("\n"); } } return buffer.toString(); } }