转载请注明原文地址:http://blog.youkuaiyun.com/forwardyzk/article/details/25162835
当设置了TextView设置了可以多行显示了,比如:当显示超多了三行,那么在开始,中间或者结尾使用...代替。我们第一时间会想到设置。
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="start"
android:lines="3"
android:singleLine="false"
android:text="test" />
但是这样设置是不起到作用的,我先解释一个几个属性的作用,就i明白了。
android:lines设置文本的行数,设置几行就显示几行,即使最后几行没有数据也会显示。
android:maxLines设置文本的最大显示行数,与width或者layout_width结合使用,超出部分自动换行,超出行数将不显示。
所以我们开始那样设置,android:ellipsize="start" 是不起作用的。但是有时候android:ellipsize="end"会起到作用的。android:maxLines和android:lines结合android:ellipsize使用,其ellipsize="end"起作用,其他的值就不其作用
另外注意一点:
android:singleLine="true" ,android:ellipsize="start" 这两个属性结合使用才会其作用,ellipsize=middle/end/start才会其作用
如果要显示多行,例如:只显示三行,并且在开始位置加省略号。
main.xml
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="false"
android:text="test" />
singleLine默认是false,也可以不写。
使用代码实现:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StringBuffer sb=new StringBuffer();
for (int i = 0; i < 10; i++) {
sb.append("helloworld,世界您好");
}
TextView tv=(TextView) findViewById(R.id.tv);
tv.setText(sb.toString());
setLines(tv);
}
public void setLines(final TextView tv) {
//测试
ViewTreeObserver observer = tv.getViewTreeObserver(); //textAbstract为TextView控件
observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
// TODO Auto-generated method stub
ViewTreeObserver obs = tv.getViewTreeObserver();
obs.removeGlobalOnLayoutListener(this);
if(tv.getLineCount() > 3){
int length=tv.getText().length();
int lineEndIndex = tv.getLayout().getLineEnd(2); //设置第六行打省略号
String text = "..."+tv.getText().toString().substring(length-lineEndIndex, length) ;
tv.setText(text);
}
}
});
}
}
思路是:
先获得显示的行数,然后获得最后三行显示的长度,然后再截取字符串。
注意点:必须是先设置 tv.setText("内容");然后在使用此方法截取。
同样如果想把省略号放在中间或者结尾,那么就相应的截取字符串,然后再拼接。
提供方法:字符串的subSequence(0.index)方法。
有什么不足之处,还请大家指出!