Android gets the string width displayed in TextView, androidtextview
When there is a business at work, you need to determine whether textview has a line break. My approach is to determine whether the width of the string to be displayed in textview exceeds the width I set. If it exceeds the width, a line break is executed.
This is also required elsewhere in the project, so the code is used directly. As follows:
Public float getTextWidth (Context, String text, int textSize ){
TextPaint paint = new TextPaint ();
Float scaledDensity = Context. getResource (). getDisplayMetrics (). scaledDensity;
Paint. setTextSize (scaledDensity * textSize );
Return paint. measureText (text );
}
Here the measureText method of TextPaint is used.
However, some problems have been found in the project practice. When a string contains letters and numbers, there is a 1-2 pixel error. This error also leads to a line feed error in the code, causing an error in the interface display.
To solve this problem, I found this article
This article uses another method for measurement, instead of new TextPaint, but uses TextView's own TextPaint, which is obtained through TextView. getPaint () method.
The last example shows the difference between the two methods.
Testing Machine is MI4, xxdpi
The Code is as follows:
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
// The test example uses the 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 * 15;
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 can be seen that the true width is obtained by calling the measureText method using TextPaint of textView.