[Android实例] 适应多行长文本的Android TextView

大家经常会用到系统默认的TextView,TextView可以很好地适应单行长文本(尾部自动打上省略号),以及可以完整显示多行文本(TextView的宽高足够大)。但如果是很多行的文本而TextView又足够大的时候,则会出现以下这种情况.......超出的文本受TextView大小限制,不能完全显示。

本文主要实现一个能够适应多行长文本的TextView,自动缩减长文本并在结尾补上省略号。如下图:红色部分为普通的TextView,绿色部分为本文实现的TextView

 


本文的源码可以到 http://download.csdn.net/detail/hellogv/4298631 下载,本文的TextViewMultilineEllipse.java改自http://code.google.com/p/android-textview-multiline-ellipse/以及http://code.google.com/p/android/的MyClipTextView.java,相对于前面2者,本文使用哈希表来保存每次onMeasure()计算所得的宽高,大幅减少重复计算宽高。

本文的主Activity的源码如下:

?
代码片段,双击复制
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
public class AutoFixTextViewActivity extends Activity {
         private LinearLayout linearLayout1;
         private TextViewMultilineEllipse tvMultilineEllipse;
         private TextView tvNormal;
         
         //水调歌头,大家懂的
         private final String text= "明月几时有?把酒问青天。不知天上宫阙,今夕是何年。\n"
                         + "我欲乘风归去,又恐琼楼玉宇,高处不胜寒。\n"
                         + "起舞弄清影,何似在人间。\n"
                         + "转朱阁,低绮户,照无眠。不应有恨,何事长向别时圆?\n"
                         + "人有悲欢离合,月有阴晴圆缺,此事古难全。\n"
                         + "但愿人长久,千里共婵娟。" ;
    @Override
    public void onCreate(Bundle savedInstanceState) {
         super .onCreate(savedInstanceState);
         setContentView(R.layout.main);
         this .setTitle( "适应多行文本的Android TextView---hellogv" );
         
         //共同的宽高
         LayoutParams lp= new LayoutParams(LayoutParams.FILL_PARENT, 100 );
         //----用TextView来显示换行长文本----//
         tvNormal=(TextView) this .findViewById(R.id.tvNormal);
         tvNormal.setLayoutParams(lp); //限制TextView的宽高
         tvNormal.setEllipsize(TextUtils.TruncateAt.END);
         tvNormal.setSingleLine( false );
         tvNormal.setMaxLines( 5 );
         tvNormal.setText(text);
         
         
         //----用TextViewMultilineEllipse来显示换行长文本----//
         linearLayout1=(LinearLayout) this .findViewById(R.id.linearLayout1);
         
         tvMultilineEllipse = new TextViewMultilineEllipse( this );
                tvMultilineEllipse.setLayoutParams(lp); //限制TextView的宽高
                tvMultilineEllipse.setEllipsis( "..." ); //...替换剩余字符串
                tvMultilineEllipse.setMaxLines( 5 );
                tvMultilineEllipse.setTextSize(( int )tvNormal.getTextSize()); //设置文字大小
                tvMultilineEllipse.setTextColor(Color.WHITE);
                tvMultilineEllipse.setText(text); //设置文本
                 
                //在代码里添加tvMultilineEllipse,暂时不支持Layout里直接添加
                linearLayout1.addView(tvMultilineEllipse);
                 
    }
  
    
}


PS:TextViewMultilineEllipse是在代码里动态构建和使用,而不能直接在Layout.xml里使用。

main.xml的源码如下:
?
代码片段,双击复制
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
"1.0" encoding= "utf-8" ?>
"http://schemas.android.com/apk/res/android"
    android:layout_width= "fill_parent"
    android:layout_height= "fill_parent"
    android:orientation= "vertical" >
 
   
         android:id= "@+id/tvNormal"
         android:layout_width= "wrap_content"
         android:layout_height= "wrap_content"
         android:text= "Medium Text"
         android:textAppearance= "?android:attr/textAppearanceMedium" />
 
   
         android:id= "@+id/linearLayout1"
         android:layout_width= "match_parent"
         android:layout_height= "wrap_content"
         android:layout_marginTop= "20dip" >
   
 


TextViewMultilineEllipse.java源码如下,有点多,读者可以直接忽略:
?
代码片段,双击复制
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
public class TextViewMultilineEllipse extends TextView{
 
    private TextPaint mTextPaint;
    private String mText;
    private int mAscent;
    private String mStrEllipsis;
    private String mStrEllipsisMore;
    private int mMaxLines;
    private boolean mDrawEllipsizeMoreString;
    private int mColorEllipsizeMore;
    private boolean mRightAlignEllipsizeMoreString;
    private boolean mExpanded;
    private LineBreaker mBreakerExpanded;
    private LineBreaker mBreakerCollapsed;
    /**hashMapW是优化的关键点,通过哈希表来减少计算次数*/
    private HashMap hashMapW= new HashMap();
    public TextViewMultilineEllipse(Context context) {
         super (context);
      // TODO Auto-generated constructor stub
         mExpanded = false ;
         mDrawEllipsizeMoreString = true ;
         mRightAlignEllipsizeMoreString = false ;
         mMaxLines = - 1 ;
         mStrEllipsis = "..." ;
         mStrEllipsisMore = "" ;
         mColorEllipsizeMore = 0xFF0000FF ;
         
         mBreakerExpanded = new LineBreaker();        
         mBreakerCollapsed = new LineBreaker();
         
         // Default font size and color.
         mTextPaint = new TextPaint();
         mTextPaint.setAntiAlias( true );
         mTextPaint.setTextSize( 13 );
         mTextPaint.setColor( 0xFF000000 );
         mTextPaint.setTextAlign(Align.LEFT);
         setDrawingCacheEnabled( true );
    }
    
    /**
      * Sets the text to display in this widget.
      * @param text The text to display.
      */
    public void setText(String text) {
         mText = text;
         requestLayout();
         invalidate();
    }
 
    /**
      * Sets the text size for this widget.
      * @param size Font size.
      */
    public void setTextSize( int size) {
         mTextPaint.setTextSize(size);
         requestLayout();
         invalidate();
    }
 
    /**
      * Sets the text color for this widget.
      * @param color ARGB value for the text.
      */
    public void setTextColor( int color) {
         mTextPaint.setColor(color);
         invalidate();
    }
 
    /**
      * The string to append when ellipsizing. Must be shorter than the available
      * width for a single line!
      * @param ellipsis The ellipsis string to use, like "...", or "-----".
      */
    public void setEllipsis(String ellipsis) {
         mStrEllipsis = ellipsis;
    }
    
    /**
      * Optional extra ellipsize string. This
      * @param ellipsisMore
      */
    public void setEllipsisMore(String ellipsisMore) {
         mStrEllipsisMore = ellipsisMore;
    }
    
    /**
      * The maximum number of lines to allow, height-wise.
      * @param maxLines
      */
    public void setMaxLines( int maxLines) {
         mMaxLines = maxLines;
    }
    
    /**
      * Turn drawing of the optional ellipsizeMore string on or off.
      * @param drawEllipsizeMoreString Yes or no.
      */
    public void setDrawEllipsizeMoreString( boolean drawEllipsizeMoreString) {
         mDrawEllipsizeMoreString = drawEllipsizeMoreString;
    }
    
    /**
      * Font color to use for the optional ellipsizeMore string.
      * @param color ARGB color.
      */
    public void setColorEllpsizeMore( int color) {
         mColorEllipsizeMore = color;
    }
    
    /**
      * When drawing the ellipsizeMore string, either draw it wherever ellipsizing on the last
      * line occurs, or always right align it. On by default.
      * @param rightAlignEllipsizeMoreString Yes or no.
      */
    public void setRightAlignEllipsizeMoreString( boolean rightAlignEllipsizeMoreString) {
         mRightAlignEllipsizeMoreString = rightAlignEllipsizeMoreString;
    }
    
    /**
      * @see android.view.View#measure(int, int)
      */
    @Override
    protected void onMeasure( int widthMeasureSpec, int heightMeasureSpec) {
         setMeasuredDimension(
             measureWidth(widthMeasureSpec),
             measureHeight(heightMeasureSpec));
    }
 
    /**
      * Determines the width of this view
      * @param measureSpec A measureSpec packed into an int
      * @return The width of the view, honoring constraints from measureSpec
      */
    private int measureWidth( int measureSpec) {
         int result = 0 ;
         int specMode = MeasureSpec.getMode(measureSpec);
         int specSize = MeasureSpec.getSize(measureSpec);
 
         if (specMode == MeasureSpec.EXACTLY) {
             // We were told how big to be.
             result = specSize;
             
             // Format the text using this exact width, and the current mode.
             breakWidth(specSize);
         }
         else {
             if (specMode == MeasureSpec.AT_MOST) {
                // Use the AT_MOST size - if we had very short text, we may need even less
                // than the AT_MOST value, so return the minimum.
                result = breakWidth(specSize);
                result = Math.min(result, specSize);
             }
             else {
                // We're not given any width - so in this case we assume we have an unlimited
                // width?
                breakWidth(specSize);
             }
         }
 
         return result;
    }
 
    /**
      * Determines the height of this view
      * @param measureSpec A measureSpec packed into an int
      * @return The height of the view, honoring constraints from measureSpec
      */
    private int measureHeight( int measureSpec) {
         int result = 0 ;
         int specMode = MeasureSpec.getMode(measureSpec);
         int specSize = MeasureSpec.getSize(measureSpec);
 
         mAscent = ( int ) mTextPaint.ascent();
         if (specMode == MeasureSpec.EXACTLY) {
             // We were told how big to be, so nothing to do.
             result = specSize;
         }
         else {
             // The lines should already be broken up. Calculate our max desired height
             // for our current mode.
             int numLines;
             if (mExpanded) {
                numLines = mBreakerExpanded.getLines().size();
             }
             else {
                numLines = mBreakerCollapsed.getLines().size();
             }
             result = numLines * ( int ) (-mAscent + mTextPaint.descent())
                   + getPaddingTop()
                   + getPaddingBottom();
 
             // Respect AT_MOST value if that was what is called for by measureSpec.
             if (specMode == MeasureSpec.AT_MOST) {
                result = Math.min(result, specSize);
             }
         }
         return result;
    }
 
    /**
      * Render the text
      *

你可能感兴趣的:(Android)