5

I have added a linearlayout in a linearlayout dynamically using this code.

LinearLayout root = (LinearLayout) findViewById(R.id.root);
View child = inflater.inflate(R.layout.childrow, null);
root.addView(child , index++);

I want to add bottom margin in childview. Can I do this dynamically?

androidcodehunter
  • 21,567
  • 19
  • 47
  • 70

2 Answers2

15
View child = inflater.inflate(R.layout.childrow, null);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); 
layoutParams.setMargins(leftMargin, topMargin,rightMargin, bottomMargin);
child.setLayoutParams(layoutParams);
root.addView(child , index++);
Sherlock
  • 590
  • 7
  • 20
AndRSoid
  • 1,777
  • 2
  • 13
  • 25
  • 1
    getting null pointer exception in this line params.setMargins(leftMargin, topMargin,rightMargin, bottomMargin); – androidcodehunter Jan 06 '14 at 06:32
  • I haven't tested the code . This is how we do it. Any how what does logcat say here ??? – AndRSoid Jan 06 '14 at 06:59
  • 2
    @rAviNder It probably says "NullPointerException". Sorry, I had to. – Lo-Tan Jul 23 '14 at 03:36
  • 3
    Posting wrong, not tested code makes no point, sorry. Instead of: //LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) child.getLayoutParams(); Add: LinearLayout.LayoutParams layParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); – Yar Dec 09 '14 at 07:40
2
LayoutParams params=(LayoutParams) child.getLayoutParams();
    params.setMargins(0, 0, 0, 5);
child.setLayoutParams(params);

The params.setMargins(0, 0, 0, 5); allows to set margins for left, top, right and bottom respectively. So to set a margin to the bottom of your child view, replace 5 with a number of your choice.

Hope this will help.. :)

Anu
  • 1,884
  • 14
  • 30