Issue
I need a multi-line layout, which would behave as horizontal linear layout, but when there is not enough space to place new widget it would expand to next line, just like words in text. Widgets would be added there at runtime, and should go with wrap_content
. Actually, there would be buttons.
Is there any widgets with such behaviour? Or give a suggestion about how to write such layout by myself.
Finally it should look like this:
Solution
Check the comments: this will do the job
/*
* Copyright 2011 Sherif
*/
private void populateText(LinearLayout ll, View[] views , Context mContext) {
Display display = getWindowManager().getDefaultDisplay();
ll.removeAllViews();
int maxWidth = display.getWidth() - 20;
LinearLayout.LayoutParams params;
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 < views.length ; i++ ){
LinearLayout 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));
//my old code
//TV = new TextView(mContext);
//TV.setText(textArray[i]);
//TV.setTextSize(size); <<<< SET TEXT SIZE
//TV.measure(0, 0);
views[i].measure(0,0);
params = new LinearLayout.LayoutParams(views[i].getMeasuredWidth(),
LayoutParams.WRAP_CONTENT);
//params.setMargins(5, 0, 5, 0); // YOU CAN USE THIS
//LL.addView(TV, params);
LL.addView(views[i], params);
LL.measure(0, 0);
widthSoFar += views[i].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);
}
Answered By - Sherif elKhatib
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.