获取行数
ViewTreeObserver vto = textView.getViewTreeObserver(); vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { ViewTreeObserver obs = textView.getViewTreeObserver(); obs.removeGlobalOnLayoutListener(this); int lineCount = textview.getLineCount(); //行数 } }); //或者 textview.setText(“Some text”); textview.post(new Runnable() { @Override public void run() { int lineCount = textview.getLineCount();//行数 } });
final TextView title = (TextView)findViewById(R.id.text); title.setText("A really long text"); ViewTreeObserver vto = title.getViewTreeObserver(); vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { ViewTreeObserver obs = title.getViewTreeObserver(); obs.removeGlobalOnLayoutListener(this); if(title.getLineCount() > 3){ Log.d("","Line["+title.getLineCount()+"]"+title.getText()); int lineEndIndex = title.getLayout().getLineEnd(2); String text = title.getText().subSequence(0, lineEndIndex-3)+"..."; title.setText(text); Log.d("","NewText:"+text); } } });
获取行的内容和宽度
Layout layout = edit.getLayout(); String text = edit.getText().toString(); int start = 0; int end; for (int i = 0; i < edit.getLineCount(); i++) { end = layout.getLineEnd(i); String line = text.substring(start, end); //指定行的内容 start = end; float width = layout.getLineWidth(i); //指定行的宽度 Log.e("test", line + "," + width); }