I am trying to create multiple linear layouts inside main LinearLayout. But i am having some trouble with margin. Here is my code and output: –
public class CustomActivity extends Activity {
private LinearLayout mainLayout;
Float value;
int dpi;
private String[] data = new String[] {"Hello World", "Hello World", "Hello World", "Hello World", ""};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom);
mainLayout = (LinearLayout)findViewById(R.id.mainLayout);
mainLayout.setOrientation(LinearLayout.VERTICAL);
value = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, getResources().getDisplayMetrics());
dpi = Math.round(value);
addLayouts();
}
private void addLayouts() {
int marginBottom = 0;
int count = 0;
for (int i = 0; i < data.length; i++) {
OutLinedLL linearLayout = new OutLinedLL(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(dpi*22,dpi*35);
if(i==0)
{
linearLayout.setBackgroundColor(Color.RED);
params.setMargins(dpi*7, dpi, dpi*4, marginBottom);
linearLayout.setLayoutParams(params);
mainLayout.addView(linearLayout);
}
else
{
count += dpi*2;
Log.e("Count", count+"");
marginBottom -= (dpi*28)+count;
Log.e("Margin Bottom", marginBottom+"");
linearLayout.setBackgroundColor(Color.GREEN);
params.setMargins(dpi*7, dpi, dpi*4, marginBottom);
linearLayout.setLayoutParams(params);
mainLayout.addView(linearLayout);
}
marginBottom = 0;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_custom, menu);
return true;
}
}
Stack Trace: –
09-29 11:49:23.844: E/Count(16149): 40
09-29 11:49:23.844: E/Margin Bottom(16149): -600
09-29 11:49:23.852: E/Count(16149): 80
09-29 11:49:23.852: E/Margin Bottom(16149): -640
09-29 11:49:23.852: E/Count(16149): 120
09-29 11:49:23.852: E/Margin Bottom(16149): -680
09-29 11:49:23.852: E/Count(16149): 160
09-29 11:49:23.852: E/Margin Bottom(16149): -720
Output :- 
As you can see margin bottom isn’t same for all the layouts. I am unable to find out why its happening. I am trying to learn custom views at the moment so any help would be really appreciated.
Thanks.
I think this bit is your problem:
You are changing the amount of margin on each loop through. Just set it to a static value and all your views should have the same margin.