TextView限制最大行数,多出部分显示省略号,解决ellipsize = "end" 失效的问题

TextView限制最大行数,多出部分显示省略号,解决ellipsize =

1.重写TextView代码


package com.example.stringtest;


import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.widget.TextView;


public class CaculateText extends TextView{


private Paint mPaint;
private int mViewWidth;
private String[] mString;
private String ellipsize = "...";
private String mText;
private int mMaxLine = 2;
private int mCurrentLine = 0;
public CaculateText(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.LimitLineTextView);

//因为获取maxline属性要sdk = 16及以上版本才支持,所以自定义一个获取最大行数属性,以适配所有机型
mMaxLine = typedArray.getInt(R.styleable.LimitLineTextView_maxLine, 2);
}

@Override
protected void onDraw(Canvas canvas) {
mPaint      = getPaint();
int x = getPaddingLeft();
int y = (int) (getPaddingTop() - mPaint.ascent()); 

if(!TextUtils.isEmpty(mText)){
mString = mText.split("\n");
mViewWidth  = getMeasuredWidth() - getPaddingLeft() - getPaddingRight();
for(int  i = 0; i < mString.length; i ++){
String targetStr = mString[i];

for(int j = 0; j < mMaxLine; j ++){

if(!TextUtils.isEmpty(targetStr)){
mCurrentLine = mCurrentLine + 1;
if(mCurrentLine == mMaxLine){
int secondCharCount = mPaint.breakText(ellipsize + targetStr, true, mViewWidth, null);
if(targetStr.length() > secondCharCount - 3){
targetStr = targetStr.substring(0, secondCharCount - 3) + ellipsize;
}
canvas.drawText(targetStr, x, y, mPaint);
}else{
int charCount = mPaint.breakText(targetStr, true, mViewWidth, null);

canvas.drawText(targetStr.substring(0, charCount), x, y, mPaint);
y = y + getLineHeight();
if(targetStr.length() > charCount){
String strLeave = targetStr.substring(charCount, targetStr.length());
if(strLeave.length() > 0){
targetStr = strLeave;
}
}else{
targetStr = "";
}
}
if(mCurrentLine == mMaxLine) return;
}
}
}
}
}

@Override
public void setText(CharSequence text, BufferType type) {
super.setText(text, type);
mText = text.toString();
}


}


2.属性代码 在res 的value新建attrs.xml用于写自定义属性



    
   
       
   

    


3.使用时直接在布局引用即可

    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >


            xmlns:stringtext="http://schemas.android.com/apk/res/com.example.stringtest"
        android:id="@+id/caculate_textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="7.5dp"
        stringtext:maxLine ="3"
        android:text="一二三四五六七八九十一二三四五六七八九十12345678901234567890一二三四五六七八九123456789一二三四五六七八九123456789一二三四五六七八           九123456789一二三四五六七八九"/>





你可能感兴趣的:(Android,安卓分散知识点)