如果文本大于设备宽度,如何将文本拆分为新行?
例如。
aaaaa bbbbbbbb
BBBB
预期输出 -
AAAAA
bbbbbbbbbbbbbb
答案 0 :(得分:2)
只要在想要分割文本的地方使用“\ n”。
答案 1 :(得分:0)
以下解决方案正在运作 -
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;
}