0
votes

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?

2
What exactly is the problem? Doesn't work? Dimension not correct? (also note that you only set a 5px margin on one side, thats pretty small, easy to miss when looking at the layout)user658042
what is the problem ? your code is not working or what ?Android Killer
sorry that i forgot to mention that specifically.Problem is Margins not set when i run this.....above code supposed to add margin to the left first in the ml then for the button right? but its not happening....IronBlossom
@alextsc i give a sample margin as 5... actually the margin is incremented per iteration of a for-loop, like first iteration 45, second iteration 45*2 , i think thats quite noticeable.IronBlossom

2 Answers

1
votes

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_LEFT and ALIGN_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.LayoutParams instead of the MarginLayoutParams because the former allows these rules and has proper default values set.

Alter this line:

MarginLayoutParams ml = new MarginLayoutParams(-2,-2);

to

RelativeLayout.LayoutParams ml = new RelativeLayout.LayoutParams(-2,-2);

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.

3
votes

Alright, I'm gonna give this a shot IronBlossom; this is how I do it and I hope it works:

LinearLayout myLinearLayout = (LinearLayout)findViewById(R.id.my_linear_layout);
Button myButton = new Button(this);
// more myButton attribute setting here like text etc //

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
params.setMargins(5,0,0,0);
myLinearLayout.addView(myButton, params);

best,

-serkan