如果其他人有类似的问题并希望将未知数量的视图动态加载到现有布局中:
只需使用 a RelativeLayout
,将第一个添加View
到您想要的位置,然后将其余部分与之前添加的位置对齐。Android不会为不适合同一行的每个视图自动换行,因此您必须提前计算或尝试错误。
这是一个粗略的例子。首先是填充界面的方法的代码片段:
ArrayList<Item> listItems = item.getItems();
if( listItems != null ) {
for( Item item: listItem ) {
addItem( MyActivity.this, item, iCounterItemNumber );
iCounterItemNumber++;
}
}
这里是 addItem 方法:
private void addItem( Activity context, final Item item, int iCounterItemNumber ) {
View vItem = LayoutInflater.from(context).inflate(R.layout.layoutinflatable_item, null);
TextView txtvItemName = (TextView) vItem.findViewById(R.id.textView_itemName);
txtvItemName.setText(item.getName());
vItem.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View vItem) {
// just to show that you can set a OnClickListener
}
});
if ( iCounterItemNumber == 0 ) {
RelativeLayout.LayoutParams rlpItemParemeters = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
rlpItemParemeters.addRule(RelativeLayout.ALIGN_PARENT_TOP);
rlpItemParemeters.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
vItem.setId( 100 );
_rlItemTable.addView( vItem, rlpItemParemeters );
} else if ( iCounterItemNumber % 2 == 0 ) {
RelativeLayout.LayoutParams rlpPackageParemeters = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
rlpPackageParemeters.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
rlpPackageParemeters.addRule(RelativeLayout.BELOW, ( 100 - 2 + iCounterItemNumber ) );
vPackage.setId( 100 + iCounterItemNumber );
_rlShopPackagesTable.addView( vPackage, rlpPackageParemeters );
} else {
RelativeLayout.LayoutParams rlpPackageParemeters = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
rlpPackageParemeters.addRule(RelativeLayout.ALIGN_BOTTOM, ( 100 - 1 + iCounterItemNumber ) );
rlpPackageParemeters.addRule(RelativeLayout.RIGHT_OF, ( 100 - 1 + iCounterItemNumber ) );
vPackage.setId( 100 + iCounterItemNumber );
_rlItemTable.addView( vPackage, rlpPackageParemeters );
}
我知道你可以把它缩短一点,但它应该只是一个粗略的例子。希望很清楚我在这里做了什么。不包括不同的屏幕尺寸。要么使用您添加的不同大小的视图,要么获取屏幕大小并使用不同的方法。