2016-05-31 101 views

回答

0

試試這個方法

public void CustomEllipsize(final TextView tv, final int maxLine, final String ellipsizetext) { 

    if (tv.getTag() == null) { 
     tv.setTag(tv.getText()); 
    } 
    ViewTreeObserver vto = tv.getViewTreeObserver(); 
    vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { 

     @SuppressWarnings("deprecation") 
     @Override 
     public void onGlobalLayout() { 

      ViewTreeObserver obs = tv.getViewTreeObserver(); 
      obs.removeGlobalOnLayoutListener(this); 
      if ((maxLine+1) <= 0) { 
       int lineEndIndex = tv.getLayout().getLineEnd(0); 
       String text = tv.getText().subSequence(0, lineEndIndex - ellipsizetext.length()) + " " + ellipsizetext; 
       tv.setText(text); 
      } else if (tv.getLineCount() >= (maxLine+1)) { 
       int lineEndIndex = tv.getLayout().getLineEnd((maxLine+1) - 1); 
       String text = tv.getText().subSequence(0, lineEndIndex - ellipsizetext.length()) + " " + ellipsizetext; 
       tv.setText(text); 
      } 
     } 
    }); 

} 

,並使用此方法像這樣

final TextView txtView = (TextView) findViewById(R.id.txt); 
    String dummyText = "sdgsdafdsfsdfgdsfgdfgdfgsfgfdgfdgfdgfdgfdgdfgsfdgsfdgfdsdfsdfsdf"; 
    txtView.setText(dummyText); 
    CustomEllipsize(txtView, 2, "...[more]"); 
+0

無論需要與否,它都會在最大行中省略。 –