解决android:ellipsize="end" 异常

如果在TextView显示很长很长的字符串,可以在前台的layout文件中设置TextView的android:ellipsize=“end”/"start“/”middle“(在显示不下的字符串后端/前端/中间 加上三个点的省略号,即xxxxxxxx.../...xxxxxxxx/xxxxx...xxxx)。也可以设为marquee,滚动显示。我自己今天在设置成android:ellipsize=“end”时,在大屏手机三星S3上,正常显示xxxxxxxxx...(后面三个点),在htc等小屏幕手机上显示的却是xxxxxxxxx.(后面一个点)。

layout文件:

             <TextView
                    android:id="@+id/tv_content"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:ellipsize="end"
                    android:singleLine="true"
                    android:gravity="right"
                    android:textColor="@color/gray"
                    android:textSize="14sp" />

后来看到http://stackoverflow.com/questions/11210553/textview-ellipsize-issue,因为很多页面都用得到,所以抽象了一下,写了一个方法解决了这个问题:

public class WidgetUtil 

{

public void handleTextView(TextView textView, String textStr)
{
textView.setText(textStr);//首先要赋值一次,让系统自动处理,产生自动换行
ViewTreeObserver vto = textView.getViewTreeObserver();
MyOnGlobalLayoutListener layoutListener = new MyOnGlobalLayoutListener(textView, textStr);
vto.addOnGlobalLayoutListener(layoutListener);
}

}


class MyOnGlobalLayoutListener implements OnGlobalLayoutListener
{
private TextView textView;
private String textValue;


public MyOnGlobalLayoutListener(TextView textView, String textValue)
{
this.textView = textView;
this.textValue = textValue;
}

@Override
public void onGlobalLayout()
{
ViewTreeObserver obs = textView.getViewTreeObserver();
obs.removeGlobalOnLayoutListener(this);
if (textView.getLineCount() > 1)//如果一行显示不下而自动换行,所以要在前台文件作修改,去掉singleLine=true,否则该条件不会成立。
{
int lineEndIndex = this.textView.getLayout().getLineEnd(0);//获取被截断的字符长度
String text = textValue.subSequence(0, lineEndIndex - 3) + "...";//手动加上省略号
textView.setText(text);
}
}
}

   修改后的layout文件:

 <TextView
                    android:id="@+id/tv_content"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:ellipsize="none"  <!--改成none,不显示系统自动处理的省略号-->
                    android:gravity="right" <!--去掉singleLine=true-->
                    android:textColor="@color/gray"
                    android:textSize="14sp" />

然后在后台代码写:WidgetUtil.getInstance().handleTextView(tv_content,"aaaaaaaaaaaaaaddddddddddbbbbbbbbbbbbbbb");,这样将会显示成"aaaaaaaaaa...",变成了三个点的省略号,问题解决。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值