0

I have a code which generate several ImageView and put it on 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);
    }

But all images are in one line. I want to place it in two lines. Which layout to use and how to fix code for working correctly?

Bringoff
  • 99
  • 2
  • 11

3 Answers3

0

If I understand correctly, you want 2 seperate rows of images. So we need a base LinerLayout with a vertical orientation to hold each row, while each row consists of a LinerLayout with a horizontal orientation:

<?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> 
Vaiden
  • 15,728
  • 7
  • 61
  • 91
0

look here for explanation why it is happening:

Place two ImageViews programmatically

and look here for explanation to the last answer in this thread which talking about RelativeLayout Rules:

How to set RelativeLayout layout params in code not in xml

Community
  • 1
  • 1
Matan Dahan
  • 390
  • 5
  • 10
0

Try out as below:

        //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);
 }
GrIsHu
  • 29,068
  • 10
  • 64
  • 102