Created
March 16, 2017 08:14
-
-
Save vincent1086/52bf72856527b9a10a0732d9cdad36b9 to your computer and use it in GitHub Desktop.
Android - get TextView or EditText Size
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int deviceWidth; | |
WindowManager wm = (WindowManager) textView.getContext().getSystemService(Context.WINDOW_SERVICE); | |
Display display = wm.getDefaultDisplay(); | |
if(android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2){ | |
Point size = new Point(); | |
display.getSize(size); | |
deviceWidth = size.x; | |
} else { | |
deviceWidth = display.getWidth(); | |
} | |
TextView textView = new TextView(context); | |
textView.setPadding(padding,0,padding,padding); | |
textView.setTypeface(typeface); | |
textView.setText(text, TextView.BufferType.SPANNABLE); | |
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, textSize); | |
int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(deviceWidth, View.MeasureSpec.AT_MOST); | |
int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); | |
textView.measure(widthMeasureSpec, heightMeasureSpec); | |
return textView.getMeasuredHeight(); | |
TextPaint myTextPaint = new TextPaint(); | |
myTextPaint.setAntiAlias(true); | |
// this is how you would convert sp to pixels based on screen density | |
//myTextPaint.setTextSize(16 * context.getResources().getDisplayMetrics().density); | |
myTextPaint.setTextSize(textSize); | |
Layout.Alignment alignment = Layout.Alignment.ALIGN_NORMAL; | |
float spacingMultiplier = 1; | |
float spacingAddition = padding; // optionally apply padding here | |
boolean includePadding = padding != 0; | |
StaticLayout myStaticLayout = new StaticLayout(text, myTextPaint, deviceWidth, alignment, spacingMultiplier, spacingAddition, includePadding); | |
return myStaticLayout.getHeight(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment