我写了这个函数:
输入
线性布局 ll:
将成为您的“TexView”的布局(确保其方向是垂直的)
字符串文本:
文本
上下文 mContext
上下文
该怎么办
我评论了您必须编辑的部分
/*
* Copyright 2011 Sherif
*/
private void populateText(LinearLayout ll, String text , Context mContext) {
String [] textArray = text.split(" ");
Display display = getWindowManager().getDefaultDisplay();
ll.removeAllViews();
int maxWidth = display.getWidth() - 20;
LinearLayout.LayoutParams params; // to be used over and over
LinearLayout newLL = new LinearLayout(mContext);
newLL.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
newLL.setGravity(Gravity.LEFT);
newLL.setOrientation(LinearLayout.HORIZONTAL);
int widthSoFar = 0;
for (int i = 0 ; i < textArray.length ; i++ ){
LL = new LinearLayout(mContext);
LL.setOrientation(LinearLayout.HORIZONTAL);
LL.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.BOTTOM);
LL.setLayoutParams(new ListView.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
TV = new TextView(mContext);
TV.setText(textArray[i]);
//TV.setTextSize(size); <<<< SET TEXT SIZE
TV.measure(0, 0);
params = new LinearLayout.LayoutParams(TV.getMeasuredWidth(),
LayoutParams.WRAP_CONTENT);
//params.setMargins(5, 0, 5, 0); // YOU CAN USE THIS
LL.addView(TV, params);
LL.measure(0, 0);
widthSoFar += TV.getMeasuredWidth();// YOU MAY NEED TO ADD THE MARGINS
if (widthSoFar >= maxWidth) {
ll.addView(newLL);
newLL = new LinearLayout(mContext);
newLL.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
newLL.setOrientation(LinearLayout.HORIZONTAL);
newLL.setGravity(Gravity.LEFT);
params = new LinearLayout.LayoutParams(LL
.getMeasuredWidth(), LL.getMeasuredHeight());
newLL.addView(LL, params);
widthSoFar = LL.getMeasuredWidth();
} else {
newLL.addView(LL);
}
}
ll.addView(newLL);
}
笔记
我还没有测试过......我用它来做更复杂的事情并且它正在工作