The reason and treatment of the irregular typesetting of the automatic text-wrapping in Android TextView

Source: Internet
Author: User

The reason and treatment of the uneven text typesetting of Android TextView

Turn from:

TextView automatically wraps and the typography is uneven. Check the information, the reasons are summarized as follows:

1, half-width characters and full-width character confusion caused by: this is usually the Chinese characters and numbers, the English alphabet mixed

Workaround One:

Embox the characters in the TextView. All numbers, letters, and punctuation are all converted to full-width characters, making them two bytes with Chinese characters, so you can avoid the typographical clutter caused by the occupying position. The code for half-width to full-width is as follows: just call it.
public static string Todbc (string input) {
Char[] C = Input.tochararray ();
for (int i = 0; i< c.length; i++) {
if (c[i] = = 12288) {
C[i] = (char) 32;
Continue
}if (c[i]> 65280&& c[i]< 65375)
C[i] = (char) (C[i]-65248);
}
return new String (c);
}

Workaround Two:

Remove special characters or replace all Chinese labels with English numerals. Use regular expressions to filter all special characters, or use ReplaceAll () to replace Chinese labels with English numerals. After the conversion, you can solve the problem of typesetting confusion.

Replace, filter special characters
public static string Stringfilter (String str) throws patternsyntaxexception{
Str=str.replaceall ("", "]"). ReplaceAll ("! ","!");/ /Replace Chinese marking
String regex= "[" "]"; Clear out special characters
Pattern p = pattern.compile (regEx);
Matcher m = p.matcher (str);
Return M.replaceall (""). Trim ();
}

2. TextView when displaying Chinese punctuation marks cannot be displayed at the beginning and end of a line, and if a punctuation mark is just at the end of a line, the punctuation mark jumps to the next line along with the previous character.

Workaround: Add a space after the punctuation.

3, an English word can not be displayed in two lines (TextView in English, punctuation can be placed at the end of the line, but the English words cannot be separated).

4. If you want two lines to display the effect: there are two ways

Method One:

Modify the Android source code; Frameworks/base/core/java/android/text The following code in the Staticlayout.java file:

if (c = = "| | c = = '/T ' | |
(c = = '. ' | | c = = ', ' | | c = = ': ' | | c = = '; ') &&
(J-1 < here | |! Character.isdigit (Chs[j-1-start])) &&
(j + 1 >= Next | |! Character.isdigit (Chs[j + 1-start])) | |
(c = = '/' | | c = = '-') &&
(j + 1 >= Next | |! Character.isdigit (Chs[j + 1-start])) | |
(c >= first_cjk && isideographic (c, True) &&
J + 1 < next && Amp              Isideographic (Chs[j + 1-start], false))) {
Okwidth = w;
OK = j + 1;

if (Fittop < oktop)
Oktop = Fittop;
if (Fitascent < okascent)
Okascent = fitascent;
if (Fitdescent > Okdescent)
Okdescent = fitdescent;
if (Fitbottom > Okbottom)
Okbottom = Fitbottom;
}

get rid of it. After removing the punctuation marks can be displayed at the beginning and end of the line, the English words can also be separated in two lines display.

Method Two:

Customizing view display text

The internet has the talent to use a custom view to solve this problem, I did the experiment and summed up a bit:

To customize the view:

1) Inherit the view class or its subclasses, the example inherits the TextView class;

2) Write the constructor, get the attributes through XML (this step can be custom attributes, see routines);

3) overrides some functions of the parent class, usually the function that begins with on, and overrides the OnDraw () and Onmeasure () functions in the example;

  Here is the code

=========================mytextview2.java=============================

public class MyTextView2 extends textview{
Private final String namespace = "";
private String text;
private float textSize;
private float paddingleft;
private float paddingright;
private float marginleft;
private float marginright;
private int textcolor;
Private Paint Paint1 = new paint ();
private float textshowwidth;

Public MyTextView2 (context context, AttributeSet Attrs) {
Super (context, attrs);
Text = Attrs.getattributevalue ("", "text");
TextSize = Attrs.getattributeintvalue (namespace, "TextSize", 15);
TextColor = Attrs.getattributeintvalue (namespace, "TextColor", Color.White);
Paddingleft = Attrs.getattributeintvalue (namespace, "Paddingleft", 0);
Paddingright = Attrs.getattributeintvalue (namespace, "Paddingright", 0);
MarginLeft = Attrs.getattributeintvalue (namespace, "MarginLeft", 0);
MarginRight = Attrs.getattributeintvalue (namespace, "MarginRight", 0);
Paint1.settextsize (textSize);
Paint1.setcolor (TextColor);
Paint1.setantialias (TRUE);
Textshowwidth = (Activity) context). Getwindowmanager (). Getdefaultdisplay (). GetWidth ()-Paddingleft-paddingright- Marginleft-marginright;
}
@Override
protected void OnDraw (canvas canvas) {
int linecount = 0;
Text = This.gettext (). toString ();//.replaceall ("\ n", "\ r \ n");
if (text==null) return;
char[] Textchararray = Text.tochararray ();
Painted width
float drawedwidth = 0;
float Charwidth;
for (int i = 0; i < textchararray.length; i++) {
Charwidth = Paint1.measuretext (Textchararray, I, 1);

if (textchararray[i]== ' \ n ') {
linecount++;
drawedwidth = 0;
Continue
}
if (Textshowwidth-drawedwidth < charwidth) {
linecount++;
drawedwidth = 0;
}
Canvas.drawtext (Textchararray, I, 1, paddingleft + drawedwidth,
(LineCount + 1) * textSize, paint1);
Drawedwidth + = Charwidth;
}
SetHeight ((linecount + 1) * (int) textSize + 5);
}
}

=======================main.xml===============================

<relativelayout xmlns:android= ""
Xmlns:tools= ""
Android:layout_width= "Match_parent"
android:layout_height= "Match_parent"
Android:background= "@android: Color/black" >

<com.wigit.mytextview2
Android:id= "@+id/view"
Android:layout_width= "Fill_parent"
android:layout_height= "Fill_parent"
Android:textcolor= "@android: Color/white"
Android:textsize= "20dip"/>

</RelativeLayout>

=======================mainactivity.java=============================

Public class Mainactivity extends Activity {
MyTextView2 view;
    @Override
public void onCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);   
 
view = (MyTextView2) Findviewbyid (R.id.view);
View.settext (Getassetsstring (This, "1.txt"));
View.setmovementmethod (Scrollingmovementmethod.getinstance ());
}
Public String getassetsstring (Context context,string fileName) {
StringBuffer sb = new StringBuffer ();
/  /load
Try {
Assetmanager am = context.getassets () According to the language selection;
InputStream in = Am.open (FileName);
BufferedReader reader = new BufferedReader (new InputStreamReader (in));
String Line;  
while (line = Reader.readline ())!=null) {
Line + = ("\ n");
Sb.append (line); 
}
Reader.close ();
In.close ();
} catch (IOException e) {
E.printstacktrace ();
}
return sb.tostring ();
}
}

Causes and treatments for the uneven typesetting of text in an Android TextView

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.