Reputation: 332
How to split the text to new line if text is larger than the device width?
For eg.
aaaaa bbbbbbbb
bbbb
Expected Output-
aaaaa
bbbbbbbbbbbbbb
Upvotes: 1
Views: 619
Reputation: 332
Below solution is working -
txtUserName.post(new Runnable()
{
@Override
public void run()
{
int textviewWidth = getTextviewWidth(text, getWidthOfScreen());
int deviceWidth = getWidthOfScreen();
if (textviewWidth >= deviceWidth)
{
String userName = text.replace(" ", "\n");
txtUserName.setText(userName);
}
}
});
public int getTextviewWidth(String text, int deviceWidth)
{
txtUserName.setText(text);
int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(deviceWidth, View.MeasureSpec.AT_MOST);
int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
txtUserName.measure(widthMeasureSpec, heightMeasureSpec);
return txtUserName.getMeasuredWidth();
}
public int getWidthOfScreen()
{
DisplayMetrics displaymetrics = new DisplayMetrics();
(mContext).getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int width = displaymetrics.widthPixels;
return width;
}
Upvotes: 0