0

I'm trying to add a few images to a LinearLayout programmatically.

the xml of the image looks like this:

<ImageView
    android:id="@+id/iv_card27"
    android:layout_width="50dp"
    android:layout_height="match_parent"
    android:layout_marginLeft="5dp"
    android:layout_marginRight="5dp"
    android:scaleType="centerInside"
    app:srcCompat="@drawable/back" />

and this is my the java code I tried already:

ImageView card = new ImageView(this);

card.getLayoutParams().width = 50;
card.getLayoutParams().height = ViewGroup.LayoutParams.MATCH_PARENT;
card.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
card.setImageResource(R.drawable.back);

bottomRow.addView(card);

However I have been struggling to add the Margins, Also Im worried about the width which I set to 50. But it should actually be 50dp. How can I accomplish this?

hata
  • 11,633
  • 6
  • 46
  • 69
LY7WAK
  • 1
  • 1
  • i would inflate the xml layout via an layout inflater. It is much more easier. If you do so, you can edit the layout later in the xml file and not in code. But if you explicit want to change programmatically, you can do so. Illya Bublyk´s answer is completply right... – JonasPTFL May 11 '20 at 18:15
  • Hmmm, I think thats the best way to go. I cant seem to replicate the layout I designed using the designer with coding. Thanks! – LY7WAK May 11 '20 at 18:26
  • No problem. If you need further help see this SO question [https://stackoverflow.com/q/2335813/9610875](https://stackoverflow.com/q/2335813/9610875) – JonasPTFL May 11 '20 at 18:29

3 Answers3

1

You can use ViewGroup.MarginLayoutParams , RelativeLayout.LayoutParams or LinearLayout.LayoutParams to set layout margin.

LayoutParams params = new LayoutParams(
            LayoutParams.WRAP_CONTENT,      
            LayoutParams.WRAP_CONTENT);
params.setMargins(left, top, right, bottom);
card.setLayoutParams(params);

https://developer.android.com/reference/android/view/ViewGroup.MarginLayoutParams

Bholendra Singh
  • 980
  • 7
  • 14
0

You have to arrange margins using particular code:

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.setMargins(xxx,xxx,xxx,xxx);
card.setLayoutParams(params);
Illya Bublyk
  • 712
  • 6
  • 21
0

for setting margin to your ImageView:

MarginLayoutParams marginParams = new MarginLayoutParams(image.getLayoutParams());
marginParams.setMargins(left_margin, top_margin, right_margin, bottom_margin);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(marginParams);

card.setLayoutParams(layoutParams);