1 PackageCom.sixin.view;2 3 ImportAndroid.content.Context;4 ImportAndroid.graphics.Canvas;5 Importandroid.text.Layout;6 Importandroid.text.StaticLayout;7 ImportAndroid.text.TextPaint;8 ImportAndroid.util.AttributeSet;9 ImportAndroid.widget.TextView;Ten One /** A * can automatically fix the TextView, solve the problem that the right text of Android comes with TextView to not be aligned - */ - Public classJustifytextviewextendsTextView { the - Private intMliney; - Private intMviewwidth; - + PublicJustifytextview (Context context, AttributeSet attrs) { - Super(context, attrs); + } A at @Override - protected voidOnLayout (BooleanChangedintLeftintTopintRightintbottom) { - Super. OnLayout (changed, left, top, right, bottom); - } - - @Override in protected voidOnDraw (canvas canvas) { -Textpaint paint =getpaint (); to Paint.setcolor (Getcurrenttextcolor ()); +Paint.drawablestate =getdrawablestate (); -Mviewwidth =getmeasuredwidth (); theString Text =(String) GetText (); *Mliney = 0; $Mliney + =gettextsize ();Panax NotoginsengLayout layout =getlayout (); - for(inti = 0; I < Layout.getlinecount (); i++) { the intLinestart =Layout.getlinestart (i); + intLineend =layout.getlineend (i); AString line =text.substring (Linestart, lineend); the + floatwidth =staticlayout.getdesiredwidth (text, Linestart, Lineend, Getpaint ()); - if(Needscale (line)) { $ drawscaledtext (canvas, Linestart, line, width); $}Else { -Canvas.drawtext (line, 0, Mliney, paint); - } the -Mliney + =getlineheight ();Wuyi } the } - Wu Private voidDrawscaledtext (Canvas canvas,intLinestart, String Line,floatlinewidth) { - floatx = 0; About if(Isfirstlineofparagraph (Linestart, line)) { $String blanks = ""; - Canvas.drawtext (Blanks, X, Mliney, Getpaint ()); - floatBW =staticlayout.getdesiredwidth (Blanks, getpaint ()); -X + =bw; A +Line = line.substring (3); the } - $ floatD = (mviewwidth-linewidth)/Line.length ()-1; the for(inti = 0; I < line.length (); i++) { theString C =string.valueof (Line.charat (i)); the floatCW =Staticlayout.getdesiredwidth (c, Getpaint ()); the Canvas.drawtext (c, X, Mliney, Getpaint ()); -X + = CW +D; in } the } the About Private BooleanIsfirstlineofparagraph (intLinestart, String Line) { the returnLine.length () > 3 && line.charat (0) = = "&& Line.charat (1) = ="; the } the + Private BooleanNeedscale (String line) { - if(line.length () = = 0) { the return false;Bayi}Else { the returnLine.charat (Line.length ()-1)! = ' \ n '; the } - } - the}
Solve the problem that the right text of Android comes with TextView is not aligned