您的位置:首页 > 其它

Textview内容过多,尾部显示省略号或【更多】

2016-01-08 15:40 375 查看
一先看图



二、TextView 内容过多,直接设置 maxLines 和ellipsize=end 效果如图 上方TextView

三、尾部添加[更多内容],一开始想通过相对布局实现,发现不太可能(若有解决方案欢迎指正)

四、解决方案:

public class AD01 extends Activity {
TextView tv;
String str = "举个例子来说明一吧,为了让大家更明白一点,比如一个铅笔盒中有一支笔,但在没有打开之前你并不知道它是什么笔,可能是铅笔也可能是钢笔,这里有两种可能,那么你就可以定义一个枚举类型来表示它";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ad02);
tv = (TextView) findViewById(R.id.tttt);
tv.setText(str);
ViewTreeObserver observer = tv.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
ViewTreeObserver obs = tv.getViewTreeObserver();
obs.removeGlobalOnLayoutListener(this);
if (tv.getLineCount() > 2) {
int lineEndIndex = tv.getLayout().getLineEnd(1);
String html = tv.getText().subSequence(0, lineEndIndex -6)
+ "……<font color='#ff0000'>[更多内容]</font>";
tv.setText(Html.fromHtml(html));
}
}
});
}
}

QQ群里小伙伴idea 写了一个自定义控件

public class AutoTextView extends TextView  {
private int tagTextColor = 0xFFFF0000;
private String tag = "...[更多内容]";
public AutoTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
ViewTreeObserver viewTreeObserver = getViewTreeObserver();
viewTreeObserver.addOnPreDrawListener(this);
 setText(getText().toString());
}
public AutoTextView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public AutoTextView(Context context) {
this(context, null);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
}
@Override
public boolean onPreDraw() {
replaceText();
return super.onPreDraw();
}
public void replaceText() {
int count=getLineCount();
if(count>2){
int st=getLayout().getLineEnd(1);
String content = getText().toString().substring(0,st);
Paint paint = new Paint();
paint.setTextSize(getTextSize());
float pointWidth = paint.measureText(tag);
char[] textCharArray = content.toCharArray();
float drawedWidth = 0;
float charWidth;
for (int i = textCharArray.length-1; i >0 ; i--) {
charWidth = paint.measureText(textCharArray, i, 1);
if (drawedWidth < pointWidth ) {
drawedWidth += charWidth;
} else {
content=content.substring(0,i)+tag;
break;
}
}

setColor(content, content.length()-6, content.length(), tagTextColor);
}
}
private void setColor(String content, int start, int end, int textColor) {
if (start <= end) {
SpannableStringBuilder s
a8b0
tyle = new SpannableStringBuilder(content);
style.setSpan(new ForegroundColorSpan(textColor), start, end,
Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
setText(style);
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: