Need to set left margin to a button object programatically.
This is the code segment:
RelativeLayout rl = (RelativeLayout) findViewById(R.id.for_button);
MarginLayoutParams ml = new MarginLayoutParams(-2,-2);
ml.setMargins(5, 0, 0, 0);
Button btn = new Button(this);
btn.setText("7");
btn.setTextColor(Color.WHITE);
btn.setBackgroundResource(R.drawable.date_button);
rl.addView(btn,ml)
I also tried
btn.setLayoutParams(ml);
rl.addView(btn);
Whats the big problem. Or is there any alternative way?
You use a RelativeLayout as the parent for the button, but you don’t specify any rules for the it where to place the button (e.g.
ALIGN_PARENT_LEFTandALIGN_PARENT_TOP).You have to set rules for position when using a RelativeLayout though, so this messes with the layout calculation. This means that you have to use
RelativeLayout.LayoutParamsinstead of theMarginLayoutParamsbecause the former allows these rules and has proper default values set.Alter this line:
to
Chances are that you also want to add rules because the default positioning values don’t suit you (views get positioned in the top left corner of the parent layout by default). You can use
RelativeLayout.LayoutParams.addRule()for that.