main.xml如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:id="@+id/textView" android:layout_width="70dip" android:layout_height="wrap_content" android:layout_centerInParent="true" android:maxLines="5" /> </RelativeLayout>
MainActivity如下:
import android.os.Bundle; import android.view.ViewTreeObserver; import android.view.ViewTreeObserver.OnGlobalLayoutListener; import android.widget.TextView; import android.app.Activity; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); init(); } private void init() { final TextView mTextView = (TextView) findViewById(R.id.textView); mTextView.setText("测试文本控件的属性" + "测试文本控件的属性" + "测试文本控件的属性" + "测试文本控件的属性"+ "测试文本控件的属性" + "测试文本控件的属性"); ViewTreeObserver viewTreeObserver = mTextView.getViewTreeObserver(); viewTreeObserver.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { ViewTreeObserver obs = mTextView.getViewTreeObserver(); obs.removeGlobalOnLayoutListener(this); int lineCount = mTextView.getLineCount(); int lineVisibleEnd = mTextView.getLayout().getLineVisibleEnd(5); String text = mTextView.getText().subSequence(0,lineVisibleEnd - 6)+ "..."; mTextView.setText(text); } }); } }