我正在以ImageViews的形式创建一个包含在RelativeLayout中的2列图像列表。 以下是它的外观图:
RelativeLayout是从ID为“@ id / cardList”的XML文件创建的;
<ScrollView
android:layout_width="220dp"
android:layout_height="350dp"
android:id="@+id/cardListScroll"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:fillViewport="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/cardList">
</RelativeLayout>
</ScrollView>
然而, ImageView 是在java类中创建的,应该继续创建,直到 while 循环中设置的TypedArray中没有更多图像。
TypedArray images = getResources().obtainTypedArray(R.array.cardImages);
RelativeLayout cardList = (RelativeLayout) findViewById(R.id.cardList);
int counter = 1;
int length = images.length();
ImageView[] cards = new ImageView[3];
RelativeLayout.LayoutParams cardAParams = new RelativeLayout.LayoutParams(215, 215);
RelativeLayout.LayoutParams cardBParams = new RelativeLayout.LayoutParams(215,215);
while (counter < length) {
cards[counter] = new ImageView(this);
if (counter % 2 != 0) {
cardAParams.setMargins(0,((counter-1)/2)*225,0,0);
cards[counter].setLayoutParams(cardAParams);
cards[counter].setImageResource(images.getResourceId(counter-1, 0));
cardList.addView(cards[counter]);
Toast.makeText(Create.this, ""+counter, Toast.LENGTH_SHORT).show();
counter++;
} else {
cardBParams.setMargins(225,((counter-2)/2)*225,0,0);
cards[counter].setLayoutParams(cardBParams);
cards[counter].setImageResource(images.getResourceId(counter-1, 0));
cardList.addView(cards[counter]);
Toast.makeText(Create.this, ""+counter, Toast.LENGTH_SHORT).show();
counter++;
}
}
images.recycle();
我已经能够在列表中成功创建两个图像,但不会超过这个,这意味着当我需要多个时,我只能创建一行。 (我通过改变测试了这个“while(counter&lt; 3){”to“while(counter&lt; = 3)”。
我的假设是 cards [] 数组中的每个新 ImageView 都需要相应的 RelativeLayout.LayoutParams 。我尝试创建一个 RelativeLayout.LayoutParams cardsParams [] 的数组但是无法让它工作。