<TextView
android:id="@+id/textView4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:maxLines="2"
android:ellipsize="end"
android:text="This is a text of TextView This is a text of TextView This is a text of TextView This is a text of TextView This is a text of TextView"
android:textSize="20sp" />
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textView = (TextView)findViewById(R.id.textView4);
Layout layout = textView.getLayout();//此时的layout为null,必须用观察者模式的回调函数来获取layout
System.out.println("layout是"+layout);//此处为null
ViewTreeObserver observer = textView.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
boolean isfirstRunning = true;
@Override
public void onGlobalLayout() {//此方法会被调用两次,每执行一次settext就会执行一次,第一次是显示全部的文本,不加省略,第二次是加上省略,将会删减两次文本
// TODO Auto-generated method stub
if(isfirstRunning==false)return;//如果不加这一行的条件,出来之后是完整单词+。。。,如果加上,出来就是截断的单词+。。。
Layout layout2 = textView.getLayout();
System.out.println("layout2是"+layout2);
if(textView!=null&&layout2!=null){
int lines = layout2.getLineCount();
System.out.println("当前行数是"+layout2.getLineCount());
System.out.println("被省略的字符数量是"+layout2.getEllipsisCount(lines-1));//看看最后一行被省略掉了多少
System.out.println("被省略的字符起始位置是"+layout2.getEllipsisStart(lines-1));//看看最后一行被省略的起始位置
System.out.println("最后一个可见字符的偏移是"+layout2.getLineVisibleEnd(lines-1));
//开始替换系统省略号
if(lines<2)return;//如果只有一行,就不管了
if(layout2.getEllipsisCount(lines-1)==0)return;//如果被省略的字符数量为0,就不管了
String showText = textView.getText().toString();
System.out.println("删减前"+showText);
showText = showText.substring(0, layout2.getLineVisibleEnd(lines-1)-6).concat("。。。");//在此处自定义要显示的字符
System.out.println("删减后"+showText);
textView.setText(showText);
isfirstRunning=false;
}
}
});
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有