Search code examples
androidandroid-layoutandroid-relativelayout

How to set two images next to each other without using a LinearLayout?


So say I have two ImageViews. Without a LinearLayout, what's the easiest way/best way to set them next to each other programatically? (I'm using a RelativeLayout)

Currently, what I have is two ImageViews, one named A, and the other named B.

A is drawn first, then B.

What I did was :

B.setTranslationX(A.getRight());

What this is SUPPOSED to do is set B's X coordinate of the left side to A's X coordinate of its right side, which would put them next to each other.

But when I do this, I get 0 for both A's left, A's right, B's left, and B's right.

So in actuality, A and B are on top of each other, which is not what I want.


Solution

  • Try this:

    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
    ImageView iv1 = new ImageView(context);
    ImageView iv2 = new ImageView(context);
    
    your_relative_layout.addView(iv1, layoutParams);
    layoutParams.addRule(RelativeLayout.RIGHT_OF, iv1.getId());
    your_relative_layout.addView(iv2, layoutParams);
    

    This code adds a rule to the LayoutParams that iv2 would be to the right of iv1