This article determines whether the width of the string to be displayed in the textview exceeds the width I set. If it exceeds the line break, the specific code is explained as follows:
There are also such requirements in other places in the project, so the code of that piece is directly used.
public float getTextWidth(Context Context, String text, int textSize){ TextPaint paint = new TextPaint(); float scaledDensity = ().getDisplayMetrics().scaledDensity; (scaledDensity * textSize); return (text); }
Here is the measureText method using TextPaint.
However, there are some problems with this method in project practice. When a string has alphanumeric characters, there will be an error of 1-2 pixels. It is also this error that causes the code to judge the line break error, causing an error to be displayed on the interface.
To solve this problem, I found this article.
This article uses another method to measure. There is no new TextPaint, but TextView's own TextPaint, which is obtained through the() method.
Finally, we will 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) { (savedInstanceState); setContentView(.activity_main);
// Test string
// All test examples use font size of 15sp
String text = "Test Chinese";
TextView textView = (TextView) findViewById(); (text); int spec = (0, ); (spec, spec); // getMeasuredWidth int measuredWidth = (); // new textpaint measureText TextPaint newPaint = new TextPaint(); float textSize = getResources().getDisplayMetrics().scaledDensity * 15; (textSize); float newPaintWidth = (text); // textView getPaint measureText TextPaint textPaint = (); float textPaintWidth = (text); (TAG, "Test string:" + text); (TAG, "getMeasuredWidth:" + measuredWidth); (TAG, "newPaint measureText:" + newPaintWidth); (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 can be seen that the width obtained by calling the measureText method using TextPaint of textView is the true width.
Through the above code, we can successfully solve the width of the TextView display string, and I hope it will be helpful to everyone.