This article by the judge TextView to display the width of the string is more than I set the width, if more than the execution line, the specific code explained as follows:
Other parts of the project also have such a requirement, so use that piece of code directly.
Public float Gettextwidth (context context, String text, int textsize) {
Textpaint paint = new Textpaint ();
float scaleddensity = Context.getresource (). Getdisplaymetrics (). scaleddensity;
Paint.settextsize (scaleddensity * textsize);
return Paint.measuretext (text);
Here is the Measuretext method using the Textpaint.
However, there are some problems with this method in the project practice. When the string is alphanumeric, there is a 1-2 pixel error. It is precisely this error that leads to the code to Judge line-wrapping errors, making the interface display error.
To solve this problem, I found this article and poked me.
In this article, another method was used to measure, without the new textpaint, instead of using TextView's own textpaint, the paint was obtained by the Textview.getpaint () method.
Finally, give an example to see the difference between the two methods.
The test machine is mi4,xxdpi
public class Mainactivity extends activity {
Private final static String TAG = "mainactivity";
@Override
protected void onCreate (Bundle savedinstancestate) {
super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
Test string
Test examples are in 15sp font size
String Text = "Test Chinese";
TextView TextView = (TextView) Findviewbyid (r.id.test);
Textview.settext (text);
int spec = Measurespec.makemeasurespec (0, measurespec.unspecified);
Textview.measure (spec, spec);
getmeasuredwidth
int measuredwidth = Textview.getmeasuredwidth ();
New Textpaint measuretext
textpaint newpaint = new Textpaint ();
float textsize = getresources (). Getdisplaymetrics (). scaleddensity *;
Newpaint.settextsize (TEXTSIZE);
float newpaintwidth = newpaint.measuretext (text);
TextView getpaint measuretext
textpaint textpaint = Textview.getpaint ();
float textpaintwidth = textpaint.measuretext (text);
LOG.I (TAG, "test string:" + text);
LOG.I (TAG, "getmeasuredwidth:" + measuredwidth);
LOG.I (TAG, "Newpaint measuretext:" + newpaintwidth);
LOG.I (TAG, "TextView getpaint measuretext:" + textpaintwidth);
}
When the test string is: "Test Chinese", the result is as follows
Test string: Test Chinese
getmeasuredwidth:180
measuretext:180.0
Getpaint measuretext:180.0
When the test string is: "Test English ABCD",
Test string: Test English ABCD
getmeasuredwidth:279
Newpaint measuretext:278.0
TextView Getpaint measuretext:279.0
It is visible that the width of the Textpaint call Measuretext method using TextView is the true width.
Through the above code can successfully resolve the TextView display string width, I hope to help.