我有一个包含线性布局的水平滚动视图。像这样的东西:
<HorizontalScrollView
android:fillViewport="true"
android:id="@+id/product_hsv"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:measureAllChildren="false"
android:scrollbars="none">
<LinearLayout
android:id="@+id/product_container_layout"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="horizontal" />
</HorizontalScrollView>
我想做的是添加n个相同的布局以在水平滚动视图中显示产品集合。
下图将使您大致了解我到目前为止所做的事情。
为此,我已将产品收藏视图添加到R.id.product_container_layout
。
String[] productCollectionArr = new String[]{"Shirt", "Jewellary", "Moto X Play", "Ellis Flat"};
for (int i = 0; i < productCollectionArr.length; i++) {
LinearLayout parentLayout = (LinearLayout) findViewById(R.id.product_container_layout);
View child = getLayoutInflater().inflate(R.layout.item_product, null);//child.xml
parentLayout.addView(child);
}
for (int i = 0; i < productCollectionArr.length; i++) {
LinearLayout eachProductLayout = (LinearLayout) findViewById(R.id.product_container_layout);
((TextView) eachProductLayout.findViewById(R.id.product_name_tv)).setText(productCollectionArr[i]);
}
但是问题在于传递价值。由于添加到product_container_layout的每个视图都具有相同的ID。因此,只有第一个元素才能从产品集合数组中获取值。
我能做的是为每个视图及其元素生成视图ID,并将这些ID映射到特定名称,以便我可以通过ID访问它们。
这是正确的方法还是我应该做些其他事情?
因此,您需要先填充视图,然后再添加到容器或保存指向所有项目的链接。它看起来像这样:
LinearLayout parentLayout=(LinearLayout)findViewById(R.id.linearLayout1);
for (int i = 0; i < items.size(); i ++) {
View child = getLayoutInflater().inflate(R.layout.item_grid, null);//child.xml
((TextView) child.findViewById(R.id.name)).setText(items.get(i).getName(); // where R.id.name is a textView in your child.xml layout.
parentLayout.addView(child);
}
毕竟,如果要更改它,则可以按索引访问元素:
parentLayout.getChildAt(index)
但是,如果您有很多物品,那不是一个好主意。在这种情况下,您将不会回收视图,并且会占用大量内存。我建议使用支持库中的recyclerview。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句