我正在尝试创建一个视图,该视图将从适配器获取数据并将其按行彼此相邻分布。视图应该依靠它的宽度来决定何时将元素放在下一行。请看一下我正在努力实现的目标。
http://i43.tinypic.com/2w327bq.png
我在这里找到了一些很棒的代码:Android - 多行线性布局它动态生成线性布局(将水平布局放在垂直布局内)。但是,我想将所有这些数据保存在一个视图中并在其上设置一个适配器。对于如何实现这一目标的任何建议,我将不胜感激。
引用线程的代码片段:
/**
* Copyright 2011 Sherif
* Updated by Karim Varela to handle LinearLayouts with other views on either side.
* @param linearLayout
* @param views : The views to wrap within LinearLayout
* @param context
* @param extraView : An extra view that may be to the right or left of your LinearLayout.
* @author Karim Varela
**/
private void populateViews(LinearLayout linearLayout, View[] views, Context context, View extraView)
{
extraView.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
// kv : May need to replace 'getSherlockActivity()' with 'this' or 'getActivity()'
Display display = getSherlockActivity().getWindowManager().getDefaultDisplay();
linearLayout.removeAllViews();
int maxWidth = display.getWidth() - extraView.getMeasuredWidth() - 20;
linearLayout.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams params;
LinearLayout newLL = new LinearLayout(context);
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(context);
LL.setOrientation(LinearLayout.HORIZONTAL);
LL.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
LL.setLayoutParams(new ListView.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
views[i].measure(0, 0);
params = new LinearLayout.LayoutParams(views[i].getMeasuredWidth(), LayoutParams.WRAP_CONTENT);
params.setMargins(5, 0, 5, 0);
LL.addView(views[i], params);
LL.measure(0, 0);
widthSoFar += views[i].getMeasuredWidth();
if (widthSoFar >= maxWidth)
{
linearLayout.addView(newLL);
newLL = new LinearLayout(context);
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);
}
}
linearLayout.addView(newLL);
}