以编程方式将ImageView定位在两行中

时间:2013-11-18 08:26:26

标签: android android-layout imageview

我有一个生成多个ImageView并将其放在Layout上的代码。

for (int i = 0; i < NUMBER_OF_MATCHES; i++) {
        imageView = new ImageView(this);
        if (random.nextBoolean()) {
        imageView.setImageResource(R.drawable.match);
        } else {
            imageView.setImageResource(R.drawable.match_inverse);

        }
        gameLinearLayout.addView(imageView, 0, params);
    }

但所有图像都在一行中。我想把它分成两行。使用哪种布局以及如何修复代码以便正常工作?

3 个答案:

答案 0 :(得分:0)

如果我理解正确,您需要2个单独的图像行。 所以我们需要一个具有垂直方向的基本LinerLayout来保存每一行,而每一行都包含一个水平方向的LinerLayout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/gameLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/row1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" />

    <LinearLayout
        android:id="@+id/row2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" />

</LinearLayout> 

答案 1 :(得分:0)

在这里查看解释原因:

Place two ImageViews programmatically

并在这里查看解释RelativeLayout规则的最后一个答案:

How to set RelativeLayout layout params in code not in xml

答案 2 :(得分:0)

试试如下:

        //LinearLayOut Setup
        LinearLayout linearLayout= new LinearLayout(this);
        linearLayout.setOrientation(LinearLayout.VERTICAL);

        linearLayout.setLayoutParams(new LayoutParams(
                LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT));
    for (int i = 0; i < NUMBER_OF_MATCHES; i++) 
     {
        //ImageView Setup
        ImageView imageView = new ImageView(this);
        //setting image resource
  if (random.nextBoolean()) {
    imageView.setImageResource(R.drawable.match);
    } else {
        imageView.setImageResource(R.drawable.match_inverse);

    }

        //setting image position
        imageView.setLayoutParams(linearLayout);

        //adding view to layout
        linearLayout.addView(imageView);
 }