Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set margin in inflated linearlayout dynamically?

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?

like image 743
androidcodehunter Avatar asked Jan 06 '14 05:01

androidcodehunter


2 Answers

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++);
like image 156
AndRSoid Avatar answered Sep 28 '22 17:09

AndRSoid


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.. :)

like image 39
Anu Avatar answered Sep 28 '22 16:09

Anu